【问题标题】:Desserialize json with string,int array - .net core C#使用字符串、int 数组反序列化 json - .net core C#
【发布时间】:2021-03-31 02:00:24
【问题描述】:

这是我关于 stackoverflow 的第一个问题 - 到目前为止,我一直在这里找到解决方案 :)

我正在尝试反序列化 JSON 对象。问题是“计数”列表,因为元素可能会改变 - 名称和值。 我认为最好为此使用 Dictionary - 但编译器会抛出错误。

{
  "count": [
    {"apple": 2},
    {"strawberry": 8},
    {"pear": 2}
  ],
  "on_plate": true,
  "owner": "Billy"
}

我的 c# 类:

    public class FruitsDTO
    {
        public Dictionary<string, int> count { get; set; }
        public bool on_plate{ get; set; }
        public string owner{ get; set; }
    }
var respResponse = JsonConvert.DeserializeObject<FruitsDTO>(jsonObject);

结果: 无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“System.Collections.Generic.Dictionary`2[System.String,System.Int32]”,因为该类型需要 JSON 对象(例如{"name":"value"}) 以正确反序列化。

已编辑

感谢@Phuzi 和@Prasad Telkikar :)

我将班级改为:

    public class FruitsDTO
    {
        public Dictionary<string, int> count { get; set; }
        public Dictionary<string, int> Count2
            {
                get => Count.SelectMany(x => x).ToDictionary(x => x.Key, x => x.Value);
            }
        public bool on_plate{ get; set; }
        public string owner{ get; set; }
    }

Count2 - 这正是我需要的。

bool_plate - 为了这个例子,在正确的类中重命名时只是一个错字

【问题讨论】:

  • 改用List&lt;KeyValuePair&lt;string, int&gt;&gt;
  • bool_plate / on_plate 也应该有一个类型
  • @PrasadTelkikar 更新了我的评论;o)
  • 只是想知道为什么您更新的课程与答案的课程不同?

标签: c# json .net .net-core


【解决方案1】:

正如@Phuzi 所说,count 变量的类型应该是List&lt;Dictionary&lt;string, int&gt;&gt;&gt; 而不仅仅是Dictionary&lt;string, int&gt;&gt;

如果您注意到 json 对象计数属性由水果列表组成,而不是单个水果

如下更新您的 DTO,

public class FruitsDTO
{
    public List<Dictionary<string, int>> count { get; set; }  //Update type to list
    public bool on_plate { get; set; }   //update property name to on_plate
    public string owner { get; set; }
}

然后反序列化,

var respResponse = JsonConvert.DeserializeObject<FruitsDTO>(jsonObject);

【讨论】:

    【解决方案2】:

    2 个选项

    选项 1,使用带有键值对的字典。

    Option2 为 count 定义一个类。

    添加另一个类:

    public class FruitsDTO
    {
        public List<FruitCounter> count { get; set; }
        public bool bool_plate{ get; set; }
        public string owner{ get; set; }
    }
    
    public class FruitCounter
    {
        public string value { get; set; }
        public int amount { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      相关资源
      最近更新 更多