【问题标题】:Problems with an array in a class while using JSON使用 JSON 时类中的数组问题
【发布时间】:2012-06-29 20:40:06
【问题描述】:

我有一个序列化问题。我希望保存和加载一个简单的 3d 数据块。我有一个包含尺寸(宽度、高度和长度)以及一个 3D 整数数组的类。 JSON 非常乐意将类转换为字符串以供我保存,但再次转换回来时效果不佳。

数据类:

Public class cClusterData {
public int mWidth;
public int mHeight;
public int mLength;
public int[,,] mCellType;

public cClusterData()
{
    mCellType = new int[32,32,32];
}
}

保存它的例程:

    public void SaveCluster()
{
    cClusterData lData = new cClusterData();
    lData.mWidth = mWidth;
    lData.mHeight = mHeight;
    lData.mLength = mLength;
    for (int lX = 0; lX < mWidth; lX++)
    {
        for (int lY = 0; lY < mHeight; lY++)
        {
            for (int lZ = 0; lZ < mLength; lZ++)
            {
                lData.mCellType[lX,lY,lZ] = (int)mCell[lX,lY,lZ].mType;
            }
        }
    }

    string lDataString = LitJson.JsonMapper.ToJson(lData);
    cFileUtils.WriteStringToFile("TestCluster", lDataString);
    Debug.Log("Done saving");
}

以及再次加载它的函数:

    public void LoadCluster()
{
    string lDataString = cFileUtils.LoadStringFromFile("TestCluster");
    cClusterData lData = new cClusterData();
    lData = LitJson.JsonMapper.ToObject<cClusterData>(lDataString);
    Debug.Log("Loaded header " + lDataString);
    // convert cluster data to actual cluster
    mWidth = lData.mWidth;
    mHeight = lData.mHeight;
    mLength = lData.mLength;

    CreateBlankCluster();
    for (int lX = 0; lX < mWidth; lX++)
    {
        for (int lY = 0; lY < mHeight; lY++)
        {
            for (int lZ = 0; lZ < mLength; lZ++)
            {
                mCell[lX,lY,lZ].SetType((cCell.eCellType)lData.mCellType[lX,lY,lZ]);
            }
        }
    }
}

一切都很好,直到它尝试访问 lData.mCellType,此时它抛出了 NullReferenceException:

NullReferenceException:对象引用未设置为对象的实例 (wrapper managed-to-managed) object:ElementAddr (object,int,int,int)

我的猜测将涉及在构造函数中设置数组的方式,而我只是在某处遗漏了一行。但我无法解决。上网吧!

【问题讨论】:

    标签: c# json unity3d


    【解决方案1】:

    我在你的代码 sn-p 中没有看到,但是你在这个类之前添加了[System.Serializable] 吗? Thisthis 都从同一个问题开始,一个自定义类,并且似乎通过将其添加到类的顶部找到了所有解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-22
      • 2023-03-06
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 2019-08-10
      • 1970-01-01
      • 2021-12-09
      相关资源
      最近更新 更多