You need to enable JavaScript to run this app. C#如何将Inventory背包数据序列化为JSON字符串并正常反序列化
优惠活动
大模型
产品
解决方案
定价
更多

C#如何将Inventory背包数据序列化为JSON字符串并正常反序列化

问题原因

  1. 你当前仅序列化单个Inventory对象,生成的是单对象JSON结构,和你期望的数组结构、InventoryList类的结构均不匹配,反序列化时会直接抛出类型不匹配异常。
  2. 你给出的期望JSON存在语法错误:对象末尾属性、数组末尾元素后都加了多余的尾部逗号,不符合标准JSON规范,也是反序列化失败的常见诱因。
  3. 若要使用InventoryList类进行反序列化,JSON结构需要外层包裹invList字段,否则和类结构无法对应。

解决方法

场景1:直接使用List<Inventory>,完全匹配你期望的数组JSON结构

序列化代码

List<Inventory> invs = new List<Inventory>()
{
    new Inventory(){ name = "cheese", amount = 5, slot = 1 },
    new Inventory(){ name = "Bread", amount = 2, slot = 4 }
};
string jsonString = JsonSerializer.Serialize(invs);

生成的标准JSON

[
  {
    "name": "cheese",
    "amount": 5,
    "slot": 1
  },
  {
    "name": "Bread",
    "amount": 2,
    "slot": 4
  }
]

反序列化代码

// 若JSON字段名和C#属性名大小写不一致,可添加忽略大小写配置
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
List<Inventory> deserializedInvs = JsonSerializer.Deserialize<List<Inventory>>(jsonString, options);
// 读取道具示例
var firstItemName = deserializedInvs[0].name;

场景2:需要使用自定义的InventoryList类

序列化代码

InventoryList invList = new InventoryList();
invList.invList.Add(new Inventory(){ name = "cheese", amount = 5, slot = 1 });
invList.invList.Add(new Inventory(){ name = "Bread", amount = 2, slot = 4 });
string jsonString = JsonSerializer.Serialize(invList);

对应的标准JSON

{
  "invList": [
    {
      "name": "cheese",
      "amount": 5,
      "slot": 1
    },
    {
      "name": "Bread",
      "amount": 2,
      "slot": 4
    }
  ]
}

反序列化代码

var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
InventoryList deserializedList = JsonSerializer.Deserialize<InventoryList>(jsonString, options);
// 读取道具示例
var firstItemName = deserializedList.invList[0].name;

内容的提问来源于stack exchange,提问作者Phill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 13:24:05