首页 > 后端开发 > C++ > 如何使用JSSONUTINE序列化和逐渐化JSON和JSON阵列?

如何使用JSSONUTINE序列化和逐渐化JSON和JSON阵列?

Linda Hamilton
发布: 2025-02-03 04:07:10
原创
643 人浏览过

在Unity中使用JsonUtility序列化和反序列化JSON和JSON数组

问题

如何使用C#在Unity中解析和处理JSON数据(单个对象和数组),特别是使用Boomlagoon.JSON、MiniJSON或JsonUtility?

解答

从Unity 5.3.3版本开始,建议使用JsonUtility处理JSON数据,因为它性能高且简单易用。

1. 单个数据对象的序列化和反序列化:

序列化:

Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";
string playerToJson = JsonUtility.ToJson(playerInstance);
登录后复制

输出:

{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}
登录后复制

反序列化:

string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = JsonUtility.FromJson<Player>(jsonString);
登录后复制

2. JSON数组的序列化和反序列化:

为了处理JSON数组,可以使用来自这个GitHub仓库的辅助类:

辅助类 - JsonHelper.cs

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;
    }
}
登录后复制

序列化:

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"}]}
登录后复制

反序列化:

string jsonString = "{\"Items\":[{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"},{\"playerId\":\"512343283\",\"playerLoc\":\"User2\",\"playerNick\":\"Rand Nick 2\"}]}";
Player[] players = JsonHelper.FromJson<Player>(jsonString);
登录后复制

其他注意事项

  • 对于以数字开头或具有数字属性的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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板