In this tutorial, you will learn how to convert an object to JSON (JSON serialization) or Deserialization (JSON text to Object). This thing is often helpful to deal with response of reset APIs or database interaction related task or to save or interact with data in unity. Let's learn JSON serialisation in Unity3d step by step:
- Make a class that you want to use as json, for example below I have created score class:
public Scores{
public int playerNo;
public string playeName;
public string playerScore
}
2. 2. Now if we want to make it
work with JSON serialize. we have to use Serializable attribute in top of the class name
[Serializable]
public Scores{
public int playerNo;
public string playeName;
public string
playerScore
}
3. 3. Create objects
of above class:
Scores scores = new Scores();
Scores. playerNo = 1;
Scores. playeName = “Faizan”;
Scores. playerScore = 100;
The object has created and now we are able to
convert it to JSON text.
4. 4. To convert the Unity C# Object to JSON string, we can use the built-in static class of Unity named JsonUtility.
Here is how it work
String jsonStr =
JsonUtility.ToJson(scores);
Note that we have used ToJson method to
convert object to JSON. The output of the above string will be like this:
‘{" playerNo ":1," playeName
":faizan," playerScore ":"100"}’
5.
Now if we want to convert
the JSON string back to Normal C# Object (deserialization) we can use FromJson method
of the same JsonUtility Class
- Scores jsonToObject = JsonUtility.FromJson<Scores>(jsonStr)
Not that jsonStr contains the full json
string that we made in step 4.
This is smallest way to do JSON seralization and deserializatiin in unity without using any third-party plugins or dependency. If you don't want to use built-in Unity3d c# serialisation classes then you can also use third party plugins or nuGet package like newtonsoft. Here is the way to import newtonsoft DLL in Unity3d.
