此问题在此处已有答案:
How to convert Json file to Dictionary using C#-Unity(1个答案)
unity c# json string to list/dictionary in 2020(1个答案)
What's the best way to loop through a JSON of sales data to create a graph in Unity?(1个答案)
3小时前关闭。
我试图在Unity C#脚本中解析具有以下结构的JSON:
{
"Location1": [
{
"text": "Hello!",
"action": "wave"
},
{
"text": "Welcome!",
}
],
"Location2": [
{
"text": "This will be fun.",
"action": "talk"
},
{
"text": "Let's go!",
"action": "happy"
}
]
}
字符串
正如你所看到的,它是一个类型为Dictionary<string, List<Dictionary<string, string>>>
的对象。注意"action"
是可选的。
我尝试实现类来解释嵌套,但无论我使用什么组合或复杂性,我似乎都无法获得非空的dialogue.path
。
using System.Collections.Generic;
using UnityEngine;
using TMPro;
[System.Serializable]
public class Event
{
public string text;
public string? action;
}
[System.Serializable]
public class Dialogue
{
public Dictionary<string, List<Event>> path;
}
public class Sinterface : MonoBehaviour
{
private Dialogue dialogue;
void Start()
{
TextAsset json = Resources.Load<TextAsset>("my_dialogue");
Functions.Log("JSON Loaded: " + json.text); // this works
dialogue = JsonUtility.FromJson<Dialogue>(json.text);
foreach (KeyValuePair<string, List<Event>> entry in dialogue.path) // NullReferenceException
{
Functions.Log("Location: " + entry.Key);
foreach (Event e in entry.Value)
{
Functions.Log("Event Text: " + e.text);
Functions.Log("Event Action: " + e.action);
}
}
}
}
型
如何正确地将这些对象从JSON中“提取”到这个C#脚本中?
1条答案
按热度按时间xfb7svmp1#
感谢@dbc对我的教育和建议使用NewtonsoftJSON(安装说明在这里)
字符串