How to parse a JSON in Unity (using C#) without using the third party plugins
In Unity, you can easily parse JSON using “ Json.Net_Newtonsoft” but if you don’t want to use a third party and do it without using it. Here are the following steps :
Step1:
Have your sample JSON ready(host it or store it locally). Below is the sample.json file we will be using and parsing it.
{"Values":[{
"Text":"aii"
},
{
"Text":"bii"
},
{
"Text":"cii"
},
{
"Text":"dii"
},
{
"Text":"eii"
}]
}
Step2:
Build data model classes according to your JSON and serialize those classes. For the above JSON following will be the classes.
[Serializable]
public class ListItem {
public Values[] Values;
}[Serializable]
public class Values
{
public string Text;
}
**The variable names should be the same as in JSON, for example, the Key in JSON is “Values” so the variable name should also be the same as in “ListItem” class. Similarly, in “Values” class we have “Text” same as “Text” Key in JSON.
If you don’t follow the above rule you will not be able to parse the JSON.
Step3:
Parse the JSON through the root class. In the above example, our List Item class is the root class and we parse it using “JSONUtility”.Once we have our JSON in the string variable (you can put it in a variable either by downloading the JSON from the server or you have the local JSON and you can read it in a variable) then we can parse it using “JSONUtility”.
In the below snippet in “json” variable, we have the whole sample JSON and this is who we can parse it and then we have printed the whole JSON elements.
Syntax:
”JsonUtility.FromJson<RootClass>(smapleJSONstringVariable)”
ListItem items = JsonUtility.FromJson<ListItem>(json);
Debug.Log(items.Values.Length);
for(int i=0;i<items.Values.Length;i++)
{
Debug.Log(items.Values[i].Text);
}
In the below GitHub repository, you can see the JSON parsing and even Circular Paginated Scroll(Will be writing a blog soon on it).
Some of the common mistakes while parsing are
- Data model classes are not serialized
- Key names in JSON and variables names in data classes are not the same.
Let me know in comments if it worked for you or not and if you have any questions.