Home >Backend Development >C++ >How to Serialize and Deserialize JSON and JSON Arrays in Unity?
Unity JSON processing: serialization and desertification
This article solves the problem of using BoomLagoon.json or Minijson library in unity, and can only read the problem of the first object or key value pair.
Solution:
<.> 1. Use Unity's built -in jsonutility:
Unity's own API simplifies JSON's serialization and dependentization process.
A single data object (non -array of JSON): JsonUtility
Capitalization:
Multiple data objects (array JSON):
<code class="language-C#">Player playerInstance = new Player(); // 设置玩家属性 string playerToJson = JsonUtility.ToJson(playerInstance);</code>
You need to use the auxiliary class (code see below).
serialization:<code class="language-C#">string jsonString = "{\"playerId\":\"1\",\"playerLoc\":\"Powai\"}"; Player player = JsonUtility.FromJson<Player>(jsonString);</code>
Capitalization:
JsonHelper
(please add it by yourself) <.> 2. No need to classify:
<code class="language-C#">Player[] playerInstance = new Player[2]; // 设置每个对象的玩家属性 string playerToJson = JsonHelper.ToJson(playerInstance, true);</code>
For JSON (for example: ) with the attribute or the number of numbers, it is recommended to use a third -party library, such as Simplejson.
<.> 3. Failure exclusion:<code class="language-C#">string jsonString = "{\"Items\":[{\"playerId\":\"1\",\"playerLoc\":\"Powai\"},{\"playerId\":\"2\",\"playerLoc\":\"Andheri\"}]}"; Player[] player = JsonHelper.FromJson<Player>(jsonString);</code>
Serialization:
Make sure that the class is not an array.
Add attribute to the class. "{15m\": 1740.01}"
from the class members.
Revitalization problem:Make sure that JSON is not an array (
[Serializable]
{ get; set; }
JsonHelper.FromJson
Lightweight library, but the maintenance update is less, and there may be limitations. [Serializable]
Through the above methods, you can effectively process JSON data in the Unity project. Remember to choose the right library and method according to your needs. The above is the detailed content of How to Serialize and Deserialize JSON and JSON Arrays in Unity?. For more information, please follow other related articles on the PHP Chinese website!