json 在 Unity C# 中反序列化

json deserialize in Unity C#

我是 JSON 的新手,我正在尝试反序列化为 JSON 数组,但出现无效值错误。 请向我解释我做错了什么。提前致谢。 下面我附上源代码和JSON文件。

using UnityEngine;

public class PageDefinitionTest : MonoBehaviour
{
public int pageNumber;
public void Start()
{
    string jsonString = 
 $"Assets/Resources/GameJSONData/Page{pageNumber}.json";
    PageDefinition def = JsonUtility.FromJson<PageDefinition>(" 
{\"data\":" + jsonString.ToString() + "}");
    Debug.Log(def);
}
}
[System.Serializable]
public class PageDefinition
{
public RectData[] data;
}

[System.Serializable]
public class RectData
{
public Rect area;
}

"areaDefinitions": [
{
  "area": {
    "serializedVersion": "2",
    "x": -3.5999999046325685,
    "y": 2.5143675804138185,
    "width": 7.199999809265137,
    "height": 1.9955297708511353
  },
  "type": 0
},
{
  "area": {
    "serializedVersion": "2",
    "x": -3.5999999046325685,
    "y": 0.21950837969779969,
    "width": 7.199999809265137,
    "height": 2.155172109603882
  },
  "type": 0
},
{
  "area": {
    "serializedVersion": "2",
    "x": -3.5999999046325685,
    "y": -1.9206972122192383,
    "width": 7.199999809265137,
    "height": 1.5465353727340699
  },
  "type": 0
},
{
  "area": {
    "serializedVersion": "2",
    "x": -3.5999999046325685,
    "y": -3.731640338897705,
    "width": 7.199999809265137,
    "height": 1.4966471195220948
  },
  "type": 0
},
{
  "area": {
    "serializedVersion": "2",
    "x": 3.5999999046325685,
    "y": 3.362467050552368,
    "width": 7.199999809265137,
    "height": 1.63633394241333
  },
  "type": 0
},
{
  "area": {
    "serializedVersion": "2",
    "x": 3.5999999046325685,
    "y": 1.097541332244873,
    "width": 7.199999809265137,
    "height": 2.3746800422668459
  },
  "type": 0
},
{
  "area": {
    "serializedVersion": "2",
    "x": 3.5999999046325685,
    "y": -1.5415465831756592,
    "width": 7.199999809265137,
    "height": 2.32479190826416
  },
  "type": 0
},
{
  "area": {
    "serializedVersion": "2",
    "x": 3.5999999046325685,
    "y": -3.7466068267822267,
    "width": 7.199999809265137,
    "height": 1.5465354919433594
  },
  "type": 0
}
]
}

我JSON序列化成功了,比看起来简单,但是反序列化不行。谢谢!

您应该将 jsonString 的文本放在 json 文件中,而不是文件路径.

对于阅读文本文件,您有多种选择:

1- 从检查员那里得到:

在您的 class 中定义一个 TextAsset,如下所示:

[SerializeField] TextAsset myfile;

您也可以为此使用 Resources.Load(resourceRelativePath)

然后像这样读取 jsonString

var jsonString = textFile.text;

2- 有准确的文件路径:(阅读关于 streamingAssets 和 PersistentDataPath 的文档:

        var jsonString = File.ReadAllText(filePath);