【问题标题】:Deserialize a JSON into a list of C# objects [duplicate]将 JSON 反序列化为 C# 对象列表 [重复]
【发布时间】:2019-10-20 20:24:48
【问题描述】:

我正在开发一个使用 Firebase 的手机游戏项目。我已经设法获得登录/注册,并将项目发送到数据库以正常工作。然而,经过无数小时的头撞墙后,我就是无法让库存工作。我可以从数据库中获取正确的 JSON 数据,格式如下:

{"5449000085757":{"itemLevel":82,"itemName":"Sword of Maximum Epicness","itemType":""},"6419800152996":{"itemLevel":45,"itemName":"Your Average Sword","itemType":""}}

当然,这些都只是用于测试目的的字段。我要做的是创建一个对象列表,其中列表是“库存”,对象是项目。我尝试过使用 Json.NET、Unity 的内置 JSON 实用程序、各种技术,但就是找不到方法。我觉得有点愚蠢,因为显然不可能这么难。无论我尝试过什么示例,它都不起作用。

如果可能,有人可以简要介绍一下如何从 JSON 创建对象列表,这是一种简单的方法吗?我只是无法自己解决这个问题,这真的很令人沮丧。

【问题讨论】:

  • 无论我尝试过什么示例,它都不起作用。 那么不起作用的代码在哪里?当您提供一个起点时,提供帮助会更容易 - 因为您已经将所有的负担都放在了我们身上。
  • 在我看来,您应该反序列化为 Dictionary 其中 item 具有 itemLevel、itemName 和 itemType 字段。
  • 您应该重新考虑 json 形状,因为它具有 id 作为类型名称。它可以工作,但我不推荐它。以下可能更合适 { "levels": [{"id": "5449000085757","itemLevel": 82,"itemName": "Sword of Maximum Epicness","itemType": ""},{"id": "6419800152996","itemLevel": 45,"itemName":"你的平均剑","itemType": ""} ] }

标签: c# json firebase unity3d json.net


【解决方案1】:

如果您想要一个使用 JSON 水合的强类型类,您可以执行以下操作:

  1. 将 JSON 负载复制到剪贴板。
  2. 在 Visual Studio 中为您的项目添加一个新类。从编辑菜单中选择选择性粘贴/将 JSON 粘贴为类。这将创建一个或多个代表您的 JSON 类的类。
  3. 打开工具/管理解决方案的 NuGet 包。将 NewtonSoft.JSON 库添加到您的项目中。
  4. 要从 JSON 中水合您的对象,请使用以下内容:

    MyObject myObject = JsonConvert.DeserializeObject(jsonPayload);

【讨论】:

    【解决方案2】:

    我会先下载Newtonsoft.Json NuGet 包。确保您使用using Newtonsoft.Json 将其导入您的班级。

    然后我会创建一个Item 类:

    public class Item
    {
        [JsonProperty("itemLevel")]
        public long ItemLevel { get; set; }
    
        [JsonProperty("itemName")]
        public string ItemName { get; set; }
    
        [JsonProperty("itemType")]
        public string ItemType { get; set; }
    }
    

    然后您可以使用 JsonConvert.DeserializeObject 简单地将您的 JSON 反序列化为 Dictionary<string, Item>

    var deserializedJson = JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);
    

    测试

    var json = "{\"5449000085757\":{\"itemLevel\":82,\"itemName\":\"Sword of Maximum Epicness\",\"itemType\":\"\"},\"6419800152996\":{\"itemLevel\":45,\"itemName\":\"Your Average Sword\",\"itemType\":\"\"}}";
    
    var deserializedJson = JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);
    
    foreach (var entry in deserializedJson)
    {
        Console.WriteLine($"Key={entry.Key}, itemLevel={entry.Value.ItemLevel}, itemName={entry.Value.ItemName}, itemType={entry.Value.ItemType}");
    }
    

    输出

    Key=5449000085757, itemLevel=82, itemName=Sword of Maximum Epicness, itemType=
    Key=6419800152996, itemLevel=45, itemName=Your Average Sword, itemType=
    

    【讨论】:

      【解决方案3】:

      最好的做法是将其反序列化为 Dictionary&lt;string, object&gt; 并遍历这些值并将它们转换为您想要的“Item”类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-30
        • 1970-01-01
        • 2022-12-13
        • 2011-12-23
        • 2022-01-19
        • 2017-06-10
        • 1970-01-01
        相关资源
        最近更新 更多