c# - Unity C# JSON 不会序列化私有二维数组?
问题描述
我已经制作了一个自定义类,我需要将其序列化为 json 文件进行保存。我已经得到它,以便它将写入文件,但除非我将数组标记为公共,否则它不会序列化数据,并且只会保存一个(大部分)空白文件。
using System;
using System.IO;
using UnityEngine;
[Serializable]
public class SettingsData
{
[SerializeField] int[,] schedule = new int[7,24]; //stores the each hour in a 2D array [day,hour]
public void Save()
{
string jsn = JsonUtility.ToJson(this);
string path = Application.persistentDataPath + "/settings.json";
Debug.Log(path);
File.WriteAllText(path, jsn);
}
}
它吐出什么:
{}
我希望它吐出什么:
{"schedule":[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]}
我尝试过其他 JSON 序列化程序(neuecc/Utf8Json 和 Newtonsoft.Json),但这些都不起作用
我尝试将其设为一维数组而不是二维数组,但没有成功。
我什至把这个函数移到了课堂之外,以防它是“(这个)”把它搞砸了,事实并非如此。
将其公开确实有效,但我希望这是私有的。
如何在不公开的情况下使其序列化?
解决方案
一维私有数组可以序列化。
[Serializable]
public class JsonDataTest
{
[SerializeField]
private int[,] schedule = new int[7, 24];
[SerializeField]
private int a = 3;
[SerializeField]
private List<int> b = new List<int>();
[SerializeField]
private int[] c = new int[9];
public void Save()
{
string jsn = JsonUtility.ToJson(this);
Debug.Log($"json string :{jsn}");
}
}
日志 :
json string:{"a":3,"b":[],"c":[0,0,0,0,0,0,0,0]}
您可以使用 MonoBehaviour,如下所示:
public class SerializeTest : MonoBehaviour
{
[SerializeField]
private int[,] schedule = new int[7, 24];
[SerializeField]
private int a = 3;
[SerializeField]
private List<int> b = new List<int>();
[SerializeField]
private int[] c = new int[9];
}
检查哪一个可以序列化。
推荐阅读
- android - 应用程序切换器终止后应用程序无法运行
- r - 我需要使用哪些函数来使用 R 来解决这个问题?
- r - 将不等长的列转换为R中的命名列表
- docker - 为什么 tty=true(in docker-compose.yml) 在 Gin 应用程序上突出显示日志?
- python - 将数据帧内容映射和更新到部分字典
- javascript - 使用响应式布局的制表符渲染问题
- python - 如何在 matplotlib 图中扩展趋势线?
- javascript - 如何使用node js比较两个.js文件的内容
- elasticsearch - 使用 Elasticsearch 组合查询
- error-handling - 如何在rust中使用if else方法出错?