繁体   English   中英

将 JSON object 数组反序列化到列表<myownclass></myownclass>

[英]Deserializing JSON object array to List<MyOwnClass>

我正在尝试阅读此 JSON 数组:

[{"name":"lc_cash","slot":1,"info":"","type":"item","amount":591},{"name":"advancedlockpick","slot":2,"info":[],"type":"item","amount":19}]

这是我的代码:

文件Inventory.cs

class Item {
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("slot")]
    public int Slot { get; set; }

    [JsonProperty("info")]
    public object Info { get; set; }

    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("amount")]
    public int Amount { get; set; }
}

class Inventory
{
    public List<Item> Item { get; set; }
}

文件Form1.cs

Inventory inventory = new Inventory();
inventory = JsonSerializer.Deserialize<Inventory>(players.Inventory);

我收到此错误:

System.Text.Json.JsonException:'JSON 值无法转换为库存。 路径:$ | 行号:0 | BytePositionInLine:1。

我怎样才能正确阅读这个?

编辑:用stackoverflow答案测试:

主要代码:

List<Item> items = new List<Item>();
items = JsonSerializer.Deserialize<List<Item>>(players.Inventory);

项目 class:

class Item {
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("slot")]
    public int Slot { get; set; }

    [JsonProperty("info")]
    public string Info { get; set; }

    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("amount")]
    public int Amount { get; set; }
}

结果:它不再抛出异常,而是只读取 0 和 nill

在此处输入图像描述

只要这里的信息是对的,你就给了我们一个 json 数组字符串。 库存是一个带有数组的 object,所以简单的解决方案是这样的:

  Inventory inventory = new Inventory();
  inventory.Item = JsonSerializer.Deserialize<List<Item>>(players.Inventory);

值得一提的是,由于Item是一个列表,因此您应该使用复数名称

您将不得不修复您的 json,其中一个属性信息具有值字符串,另一个具有数组。 你必须 select 东西一个,例如字符串

var jsonParsed = JArray.Parse(json);

foreach (var item in jsonParsed)
{
if (((JObject)item)["info"].GetType().Name == "JArray")
 ((JObject)item)["info"] = string.Empty;
}

List<Item> items = jsonParsed.ToObject<List<Item>>();

结果

[
  {
    "name": "lc_cash",
    "slot": 1,
    "info": "",
    "type": "item",
    "amount": 591
  },
  {
    "name": "advancedlockpick",
    "slot": 2,
    "info": "",
    "type": "item",
    "amount": 19
  }
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM