【问题标题】:How to serialize and deserialize complex nested json Unity?Unity如何序列化和反序列化复杂的嵌套json?
【发布时间】:2020-06-01 14:05:54
【问题描述】:

我有以下 json

{
  "android_play_store_link": "xyz",
  "ios_app_store_link": "",
  "sticker_packs": [
    {
      "identifier": "1",
      "name": "abc",
      "publisher": "Jane Doe",
      "tray_image_file": "xyz.png",
      "image_data_version":"1",
      "avoid_cache":false,
      "publisher_email":"",
      "publisher_website": "",
      "privacy_policy_website": "",
      "license_agreement_website": "",
      "stickers": [
        {
          "image_file": "abc.webp",
          "emojis": ["☕","????"]
        },
        {
          "image_file": "cdf.webp",
          "emojis": ["????","????"]
        },
        {
          "image_file": "efg.webp",
          "emojis": ["☕","????"]
        }

      ]
    }
  ]
}

直到现在我对 json 还一无所知,我该如何反序列化呢?

我知道如何从统一的持久数据路径进行基本的读写代码。但是我如何处理这个 json 呢?

我的主要目标是当玩家赢得一个关卡时,一个新的键和值将被添加到“贴纸”属性中,而且在一些关卡之后我想稍后添加对贴纸包属性的更改。

另外我将如何修改特定贴纸包项目中图像数据版本的值?

提前致谢

【问题讨论】:

  • 根据您的示例,您需要 4 个类。表情符号、贴纸、贴纸包和一些包含其他 3 个整体的类名。然后您将反序列化为包含其他类的类类型。如果使用 C# 的内置命名空间,您可以在类中使用属​​性,例如 DataContractDataMember,或者您可以导入 Nuget 包 NewtonSoft Json。信息请看这两个链接:.Net方式:(c-sharpcorner.com/article/…),NewtonSoft Json:(newtonsoft.com/json/help/html/Samples.htm
  • 关于第二个关于修改贴纸包项目中的图像数据的问题,您将deserialize json 转换为C#对象,修改所需贴纸包项目的值,然后@ 987654329@ 到 json 并保存 json 字符串。
  • 谢谢,我试试这个。

标签: c# android json unity3d json.net


【解决方案1】:

您可以使用 Newtonsoft.Json 库进行反序列化和序列化。在下面找到相应的 C# 类。

public class Sticker
{
    public string image_file { get; set; }
    public IList<string> emojis { get; set; }
}

public class StickerPack
{
    public string identifier { get; set; }
    public string name { get; set; }
    public string publisher { get; set; }
    public string tray_image_file { get; set; }
    public string image_data_version { get; set; }
    public bool avoid_cache { get; set; }
    public string publisher_email { get; set; }
    public string publisher_website { get; set; }
    public string privacy_policy_website { get; set; }
    public string license_agreement_website { get; set; }
    public IList<Sticker> stickers { get; set; }
}

public class Root
{
    public string android_play_store_link { get; set; }
    public string ios_app_store_link { get; set; }
    public IList<StickerPack> sticker_packs { get; set; }
}

要反序列化的代码:

Root root = JsonConvert.DeserializeObject<Root>(json);

【讨论】:

  • 对不起,错字了
  • 使用 IList 比使用普通列表有什么意义吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
  • 2022-01-20
相关资源
最近更新 更多