首页 > 解决方案 > 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),但这些都不起作用

我尝试将其设为一维数组而不是二维数组,但没有成功。

我什至把这个函数移到了课堂之外,以防它是“(这个)”把它搞砸了,事实并非如此。

将其公开确实有效,但我希望这是私有的。

如何在不公开的情况下使其序列化?

标签: c#jsonunity3dserializationprivate

解决方案


一维私有数组可以序列化。

[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];
}

检查哪一个可以序列化。


推荐阅读