使用字符串、int数组对json进行反序列化.net核心C#



这是我关于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对象(例如{quot;name":quot;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-为了这个例子,在正确的类中重命名时只是一个拼写错误

正如@Phuzi所说,count变量的类型应该是List<Dictionary<string, int>>>,而不仅仅是Dictionary<string, int>>

如果您注意到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此的选项

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

选项2定义计数的类。

添加另一个类:

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; }
}

最新更新