I am trying to parse a JSON with the following structure in my Unity C# script:
{
"Location1": [
{
"text": "Hello!",
"action": "wave"
},
{
"text": "Welcome!",
}
],
"Location2": [
{
"text": "This will be fun.",
"action": "talk"
},
{
"text": "Let's go!",
"action": "happy"
}
]
}
As you can see, it is an object of type (I presume) Dictionary<string, List<Dictionary<string, string>>>. Note that "action" is optional.
I tried implementing classes to interpret the nesting, but no matter what combination or complexity I've gone, I can't seem to get a non-null 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);
}
}
}
}
How do I properly "extract" these objects from my JSON into this C# script?
Dictionary<string, List<Event>> path = JsonUtility.FromJson<Dictionary<string, List<Event>>>(json.text);[System.Serializable]before theEventclass.path.Keys.Countis 0 in both cases.JsonUtility.FromJson()does not support dictionaries. See this answer by Programmer to Serialize and Deserialize Json and Json Array in Unity. But Unity now has an official port of Json.NET available. Installcom.unity.nuget.newtonsoft-jsonfrom the package manager and you should be able to doJsonConvert.DeserializeObject<Dictionary<string, List<Event>>>(json.text).