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:
Player playerInstance = new Player(); playerInstance.playerId = "8484239823"; playerInstance.playerLoc = "Powai"; playerInstance.playerNick = "Random Nick"; string playerToJson = JsonUtility.ToJson(playerInstance);
<.> 2. The serialization and derivative of the JSON array:
{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}
In order to handle the JSON array, you can use the auxiliary class from this github warehouse:
<辅> Auxiliary class -jsonhelper.csstring jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}"; Player player = JsonUtility.FromJson<Player>(jsonString);
<序> serialization:
Output: <<> <序> Capitalization:
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; } }
Other precautions <其他>
<以> For JSON with digital or digital attributes: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);
{"Items":[{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"},{"playerId":"512343283","playerLoc":"User2","playerNick":"Rand Nick 2"}]}
attributes, and members are not defined as attributes (delete ).
string jsonString = "{\"Items\":[{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"},{\"playerId\":\"512343283\",\"playerLoc\":\"User2\",\"playerNick\":\"Rand Nick 2\"}]}"; Player[] players = JsonHelper.FromJson<Player>(jsonString);
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!