Unity C# JSON 不会序列化私有二维数组?
Posted
技术标签:
【中文标题】Unity C# JSON 不会序列化私有二维数组?【英文标题】:Unity C# JSON won't serialize a private 2D array? 【发布时间】:2021-02-27 05:12:13 【问题描述】:我已经创建了一个自定义类,我需要将它序列化为一个 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),但都不起作用
我尝试将其设为一维数组而不是二维数组,但没有成功。
我什至把这个函数移到了课堂之外,以防是“(this)”把它搞砸了,事实并非如此。
将其公开确实有效,但我希望它是私有的。
如何在不公开的情况下使其序列化?
【问题讨论】:
我不习惯统一 json utils,但通常在这种情况下,我会创建一个单独的 json 文件模型类,其中包含用于序列化的公共属性 【参考方案1】:一维私有数组可以序列化。
[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];
检查哪一个可以序列化。
【讨论】:
【参考方案2】:来自Unity documentation:
Internally, this method uses the Unity serializer; therefore the object you pass in must be supported by the serializer: it must be a MonoBehaviour, ScriptableObject, or plain class/struct with the Serializable attribute applied. The types of fields that you want to be included must be supported by the serializer; unsupported fields will be ignored, as will private fields, static fields, and fields with the NonSerialized attribute applied.
这基本上意味着你不能序列化任何你无法在单一行为中序列化的东西。
Netonsoft 的 Json.net 支持这一点,你需要做两件事:
-
将班级标记为
[JsonObject]
用[JsonProperty]
标记您希望序列化的每个字段
【讨论】:
以上是关于Unity C# JSON 不会序列化私有二维数组?的主要内容,如果未能解决你的问题,请参考以下文章
如何反序列化包含同一类嵌套的json类(Unity C#)?
使用 LitJson 在 C# 中反序列化 JSON 对象数组 [重复]