Hello!
I am trying to convert an array from a json file to an unity c# array. I know how to read a json file without arrays, but i want to read the arrays as to seperate things.
Here is my json file:
{
"events":[{
"id":1,
"name":"EVENT_1",
"path":"/Events/event1.json"
},{
"id":2,
"name":"EVENT_2",
"path":"/Events/event2.json"
}]
}
I want it to convert to a c# array of [events.1, events.2], then be able to read the events data with something like events.1.path or events.1.name
Any help appreciated!
You can use Unity’s JsonUtility by defining a class that represents one of your events. Your json data would require the following classes:
[System.Serializable]
public class CEvent
{
public int id;
public string name;
public string path;
}
[System.Serializable]
public class CRoot
{
public CEvent[] events;
}
Now you can do:
CRoot root = JsonUtility.FromJson<CRoot>(YourJSONString);
You can access the first event like this:
Debug.Log( root.events[0].name );
You can check how many events are in that array like usual: root.events.Length
Hi, you can check this answer on stackoverflow, there is detailed answer about list in json and how to solve it. It helped solve my problem with this: json - Unity C# JsonUtility is not serializing a list - Stack Overflow