【发布时间】: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<KeyValuePair<string, int>> -
bool_plate/on_plate也应该有一个类型 -
@PrasadTelkikar 更新了我的评论;o)
-
只是想知道为什么您更新的课程与答案的课程不同?