【发布时间】:2020-01-06 17:44:27
【问题描述】:
我正在尝试使用 Unity 的 JSON 实用程序读取 JSON 文件,该文件如下所示:
{ "entries": [{
"2019": [{
"january": [{
"6": [{
"name": "Litago",
"ingredients": [{
"kaloriar": "20",
"salt": "10"
}]
}]
}]
}]
}]
}
我对如何设置嵌套类有点苦恼。我目前正在这样做,但它不起作用。
[System.Serializable]
public class Entries
{
public KeyValuePair<string, List<Year>> Year;
}
[System.Serializable]
public class Year
{
public KeyValuePair<string, List<Month>> Month;
}
[System.Serializable]
public class Month
{
public KeyValuePair<string, List<Day>> Day;
}
[System.Serializable]
public class Day
{
public KeyValuePair<string, List<Meal>> Meal;
}
[System.Serializable]
public class Meal
{
public string Name;
public List<KeyValuePair<string, string>> ingredients;
}
我是这样读取 JSON 的:
Entries entries = JsonUtility.FromJson<Entries>(JSONString);
理想情况下,我想做这样的事情:
Debug.Log(entries["2019"]["January"]["6"]["name"]); // Should print "Litago"
但由于我的课程很可能没有正确设置,我会收到类型错误。任何想法都将不胜感激,欢迎提出其他更好的插件来读取 JSON 的建议!
【问题讨论】:
-
你能发布你得到的错误吗?当你做点符号时会发生什么? entry.2019.January.6.name
-
JsonUtility 大部分都很好(tm),但如果你想要另一个插件,Json Dot Net。
-
不知道如何使用
JsonUtility执行此操作,但使用 json.net 您可以使用字典列表和Meal对象列表反序列化您的 JSON,例如public class RootObject { public List<Dictionary<string, List<Dictionary<string, List<Dictionary<string, List<Meal>>>>>>> Entries { get; set; } }。请参阅:dotnetfiddle.net/ld5BaB。这是否回答你的问题?老实说,JSON 有点尴尬,你有机会简化格式吗? -
无论您使用哪种序列化程序,我确定您不想要
KeyValuePair<string, List<T>>,您会想要一个字典列表。 -
AFAIK Unity 的 JsonUtility 无法直接处理嵌套类型、列表、字典、KeyValuePairs 等。来自文档 -
Passing other types directly to the API, for example primitive types or arrays, is not currently supported. For now you will need to wrap such types in a class or struct of some sort.。 Newtonsoft 可以以更健壮和直观的方式处理这样的 JSON,我建议改用它。