Home >Backend Development >C++ >How to Serialize and Deserialize JSON and JSON Arrays in Unity using JsonUtility?
JSONUTILITY serialization and desertation JSON and JSON arrays are used in Unity.
QuestionAnswer
Starting from version of Unity 5.3.3, it is recommended to use JSONUTILITY to process JSON data because it has high performance and easy use.
serialization:
Output: Capitalization:
<code class="language-csharp">Player playerInstance = new Player(); playerInstance.playerId = "8484239823"; playerInstance.playerLoc = "Powai"; playerInstance.playerNick = "Random Nick"; string playerToJson = JsonUtility.ToJson(playerInstance);</code>
<.> 2. The serialization and derivative of the JSON array:
<code class="language-json">{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}</code>
In order to handle the JSON array, you can use the auxiliary class from this github warehouse:
Auxiliary class -jsonhelper.cs<code class="language-csharp">string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}"; Player player = JsonUtility.FromJson<Player>(jsonString);</code>
serialization:
Output: Capitalization:
<code class="language-csharp">public static class JsonHelper { public static T[] FromJson<T>(string json) { Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json); return wrapper.Items; } public static string ToJson<T>(T[] array) { Wrapper<T> wrapper = new Wrapper<T>(); wrapper.Items = array; return JsonUtility.ToJson(wrapper); } private class Wrapper<T> { public T[] Items; } }</code>
Other precautions
For JSON with digital or digital attributes:<code class="language-csharp">Player[] players = new Player[2]; players[0] = new Player { playerId = "8484239823", playerLoc = "Powai", playerNick = "Random Nick" }; players[1] = new Player { playerId = "512343283", playerLoc = "User2", playerNick = "Rand Nick 2" }; string playersToJson = JsonHelper.ToJson(players);</code>You can consider using Simplejson in Unity Wiki.
<code class="language-json">{"Items":[{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"},{"playerId":"512343283","playerLoc":"User2","playerNick":"Rand Nick 2"}]}</code>ensure that the class is not an array, has
attributes, and members are not defined as attributes (delete ).
<code class="language-csharp">string jsonString = "{\"Items\":[{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"},{\"playerId\":\"512343283\",\"playerLoc\":\"User2\",\"playerNick\":\"Rand Nick 2\"}]}"; Player[] players = JsonHelper.FromJson<Player>(jsonString);</code>
The above is the detailed content of How to Serialize and Deserialize JSON and JSON Arrays in Unity using JsonUtility?. For more information, please follow other related articles on the PHP Chinese website!