Unity Json Serialization or Deserialization for Beginners

 In this tutorial, you will learn how to convert an object to JSON (JSON serialization) or Deserialization (JSON text to an Object). This thing is often helpful to deal with the response of REST APIs or database interaction-related tasks or to save or interact with data in unity. Let's learn JSON serialization in Unity3d step by step:

Unity JSON serialization Step by Step

  1. Make  a class that you want to use as JSON, for example below I have created a score class with three variables:

public Scores{

public int playerNo;

public string  playeName;

public string playerScore

}

2.     2.  Now if we want to make it work with JSON serialization. we have to use Serializable attribute on top of the class name (see below):

[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 been 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 works:

String jsonStr = JsonUtility.ToJson(scores);

Note that we have used ToJson method to convert object to JSON (Seralization). The output of the above string will be like the string (given below):

‘{" 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

  1. Scores jsonToObject = JsonUtility.FromJson<Scores>(jsonStr)

Not that jsonStr contains the full JSON string that we made in step 4.

This is the smallest way to do JSON serialization and deserialization in unity without using any third-party plugins or dependencies. If you don't want to use built-in Unity3d C# serialization classes then you can also use third-party plugins or NuGet packages like NewtonSoft. Here is the way to import newtonsoft DLL in Unity3d.

 

Post a Comment

0 Comments