c# - Unity:将 json 字符串反序列化为 C# 对象
问题描述
我正在尝试将 json 文件读入我的 C# 代码。json 文件包含以下字符串:
{
"allLevels": [{
"level": 1,
"name": "XXX",
"type": "XXX",
"description": "XXX",
"input": "XXX",
"key": "XXX",
"keyType": "XXX",
"output": "XXX"
},
{
"level": 2,
"name": "XXX",
"type": "XXX",
"description": "XXX",
"input": "XXX",
"key": "XXX",
"keyType": "XXX",
"output": "XXX"
}],
"funFacts": [
"XXX",
"XXXXX"
]
}
我有两个类,分别AllLevel.cs
如下ContentJson.cs
所示:
[System.Serializable]
public class AllLevel
{
public int level { get; set; }
public string name { get; set; }
public string type { get; set; }
public string description { get; set; }
public string input { get; set; }
public object key { get; set; }
public string keyType { get; set; }
public string output { get; set; }
}
using System.Collections.Generic;
[System.Serializable]
public class ContentJson
{
public IList<AllLevel> allLevels { get; set; }
public IList<string> funFacts { get; set; }
}
我能够读取 .json 文件,但无法将其分配给ContentJson
对象。下面代码片段中的调试日志只打印字符串“ContentJson”,并且任何访问对象内部内容的尝试都会给出 NullReferenceException。为什么 FromJson 无法反序列化对象。
public static void populateGamedata(string gameDataFileName)
{
if (gameDataFileName == null)
return;
// Path.Combine combines strings into a file path
// Application.StreamingAssets points to Assets/StreamingAssets in the Editor, and the StreamingAssets folder in a build
string filePath = Path.Combine(Application.streamingAssetsPath, gameDataFileName);
if (File.Exists(filePath))
{
// Read the json from the file into a string
string dataAsJson = File.ReadAllText(filePath);
// Pass the json to JsonUtility, and tell it to create a ContentJson object from it
ContentJson gameData = JsonUtility.FromJson<ContentJson>(dataAsJson);
// Retrieve the levels and funfacts property of gameData
levels = gameData.allLevels;
funFacts = gameData.funFacts;
Debug.Log("dataAsJson === " + dataAsJson);
Debug.Log("gameData == " + gameData.ToString());
Debug.Log("levels == " + levels[0].name);
}
else
{
Debug.LogError("Cannot load game data!");
}
}
解决方案
推荐阅读
- javascript - 如何判断输入范围元素在拖动时是增加还是减少
- python - 如何从 Python 成功保存高分辨率图像
- javascript - 如何将每个 ajax 调用中的变量传递到 1 drawchart 函数中
- laravel - Vuejs - 发布文件不起作用 - Laravel Spark
- javascript - 使用哪个 JS 以及如何实现 SVG 文本中的图像弹出?
- angularjs - 在 PHP 中使用 Angular 保存动态创建的表单数据
- vb.net - 是否有任何方法以编程方式在 Vb.NET 中编辑/添加代码?
- c++ - 使用 cout 打印字符串数组不起作用
- java - Java 返回一个已删除的文件
- scala - 来自 Akka Actor 的异步回调