将JSON解析为C#对象[复制]

j5fpnvbx  于 12个月前  发布在  C#
关注(0)|答案(1)|浏览(188)

此问题在此处已有答案

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#脚本中?

xfb7svmp

xfb7svmp1#

感谢@dbc对我的教育和建议使用NewtonsoftJSON(安装说明在这里)

using UnityEngine;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Sinterface : MonoBehaviour
{
    [SerializeField]
    private TextAsset jsonFile;

    [System.Serializable]
    public class Event
    {
        public string text;
        public string? action;
    }

    public Dictionary<string, List<Event>> dialogue;

    void Start()
    {
        if (jsonFile != null)
        {
            string jsonString = jsonFile.text;
            dialogue = JsonConvert.DeserializeObject<Dictionary<string, List<Event>>>(jsonString);
        }
        else
        {
            Debug.LogError("JSON file is not assigned in Unity Inspector");
        }

        foreach (string locationName in dialogue.Keys)
        {
            Debug.Log(locationName);
        }
    }
}

字符串

相关问题