首頁 > 後端開發 > C++ > 如何使用JSSONUTINE序列化和逐漸化JSON和JSON陣列?

如何使用JSSONUTINE序列化和逐漸化JSON和JSON陣列?

Linda Hamilton
發布: 2025-02-03 04:07:10
原創
587 人瀏覽過

在Unity中使用JsonUtility序列化和反序列化JSON和JSON數組

問題

如何使用C#在Unity中解析和處理JSON數據(單個對象和數組),特別是使用Boomlagoon.JSON、MiniJSON或JsonUtility?

解答

從Unity 5.3.3版本開始,建議使用JsonUtility處理JSON數據,因為它性能高且簡單易用。

1. 單個數據對象的序列化和反序列化:

序列化:

<code class="language-csharp">Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";
string playerToJson = JsonUtility.ToJson(playerInstance);</code>
登入後複製

輸出:

<code class="language-json">{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}</code>
登入後複製

反序列化:

<code class="language-csharp">string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = JsonUtility.FromJson<Player>(jsonString);</code>
登入後複製

2. JSON數組的序列化和反序列化:

為了處理JSON數組,可以使用來自這個GitHub倉庫的輔助類:

輔助類 - JsonHelper.cs

<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>
登入後複製

序列化:

<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>
登入後複製

輸出:

<code class="language-json">{"Items":[{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"},{"playerId":"512343283","playerLoc":"User2","playerNick":"Rand Nick 2"}]}</code>
登入後複製

反序列化:

<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>
登入後複製

其他注意事項

  • 對於以數字開頭或具有數字屬性的JSON:可以考慮使用Unity Wiki中的SimpleJSON。
  • JsonUtility故障排除:確保類不是數組,具有[Serializable]屬性,並且成員未定義為屬性(刪除{ get; set; })。

How to Serialize and Deserialize JSON and JSON Arrays in Unity using JsonUtility?

This revised output maintains the original image and its format, rephrases the text for improved flow and clarity, and uses consistent code formatting. The core information remains unchanged.

以上是如何使用JSSONUTINE序列化和逐漸化JSON和JSON陣列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板