[英]Deserialize json object with dynamic items in c#
I've got the following json document:我有以下 json 文档:
{
"name": "bert",
"Bikes": {
"Bike1": {
"value": 1000,
"type": "Trek"
},
"Bike2": {
"value": 2000,
"type": "Canyon"
}
}
}
With potentially other bikes like Bike3...BikeN.可能还有其他自行车,例如 Bike3...BikeN。 I want to deserialize to c# objects.我想反序列化为 c# 对象。 Problem is that in the deserialization step the bikes data is completely lost, resulting in a null Bikes collection.问题是在反序列化步骤中,自行车数据完全丢失,导致 null Bikes 集合。
Code to reproduce:重现代码:
[Test]
public void FirstCityJsonParsingTest()
{
var file = @"./testdata/test.json";
var json = File.ReadAllText(file);
var res = JsonConvert.DeserializeObject<Person>(json);
Assert.IsTrue(res.Name == "bert");
// next line is failing, because res.Bikes is null...
Assert.IsTrue(res.Bikes.Count == 2);
}
public class Bike
{
public string Id { get; set; }
public int Value { get; set; }
public string Type { get; set; }
}
public class Person
{
public string Name { get; set; }
public List<Bike> Bikes { get; set; }
}
To fix this problem a change in the used model is necessary.要解决此问题,需要对使用过的 model 进行更改。 But what change is needed here to fill the bikes data correctly?但是这里需要进行哪些更改才能正确填写自行车数据?
Note: Changing the input document is not an option (as it's a spec)注意:更改输入文档不是一种选择(因为它是规范)
Your code structure is not reflecting your json.您的代码结构未反映您的 json。 Common approach to deserializing json with dynamic property names is to use Dictionary<string, ...>
(supported both by Json.NET
and System.Text.Json
).使用动态属性名称反序列化 json 的常用方法是使用Dictionary<string, ...>
(由Json.NET
和System.Text.Json
支持)。 Try following:尝试以下操作:
public class Bike
{
public int Value { get; set; }
public string Type { get; set; }
}
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
public Dictionary<string, Bike> Bikes { get; set; }
}
Person.Bikes
should be changed to Dictionary<string, Bike>
(also Bike.Id
property is not needed) cause Bikes
json element is not an array but object. Person.Bikes
应更改为Dictionary<string, Bike>
(也不需要Bike.Id
属性),因为Bikes
json 元素不是数组,而是 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.