- Home /
C# Convert json arrays to unity arrys
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!
Answer by Bunny83 · Oct 05, 2017 at 11:43 PM
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
Thank you so much!
I spent almost 3hrs trying to figure this thing out, and none of the tutorial videos I found did what I needed or explained the process well enough!
it throws an error at me: JSON must represent an object type.
it throws an error at me: JSON must represent an object type.
Answer by MaxGuernseyIII · Oct 05, 2017 at 10:58 PM
Off the cuff, the Unity manual entry on JSON serialization seems to apply.
It suggests using JsonUtility.FromJson().
I am able to read the json file fine, but i want to know how to split the json file into to parts: event 1 and event 2
Answer by ryandeath189 · Jul 21, 2020 at 06:31 AM
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: https://stackoverflow.com/questions/41787091/unity-c-sharp-jsonutility-is-not-serializing-a-list
Your answer
Follow this Question
Related Questions
C# Converting json arrays using JsonUtility, 1 Answer
Help using LitJson 1 Answer
Write data to Json database using SimpleJson.cs 1 Answer
Xml Serialization? (how to read/write?) 1 Answer
Multiple Cars not working 1 Answer