[英]Deserializing this object in JSON.NET
I have the following object: 我有以下对象:
{
"pickups": {
"7": [
5,
8
],
"10": [
6,
7,
9
],
"15": [
1
],
"20": [
0,
2
],
"25": [
3,
4
]
}
}
I'd like to de-serialize each pickups element into the following object: 我想将每个皮卡元素反序列化为以下对象:
public class Pickups {
public Pickup[] pickups;
}
public class Pickup {
public int Group; // This could be the 7, 10, 15, 20, 25, etc.
public int[] Values; // If this was the "7" grouping, it would contain 5, 8.
}
As you can see from the data its a bit tricky to do this. 正如您从数据中看到的那样,这样做有些棘手。 I've been trying to use a JsonConverter to convert the object with a bit of custom code but its been a nightmare and I haven't been able to get it right. 我一直在尝试使用JsonConverter通过一些自定义代码来转换对象,但这是一场噩梦,而我一直无法正确地做到这一点。 I am wondering if anyone would know the best way to convert this type of object into the correct format I need? 我想知道是否有人会知道将这种类型的对象转换成我需要的正确格式的最佳方法?
While a converter would be a good choice you can still deserialize the Json and construct the desired object graph 虽然转换器是一个不错的选择,但是您仍然可以反序列化Json并构造所需的对象图
var root = JsonConvert.DeserializeObject<RootObject>(json);
var pickups = new Pickups {
pickups = root.pickups.Select(kvp =>
new Pickup {
Group = int.Parse(kvp.Key),
Values = kvp.Value
}
).ToArray()
};
Where 哪里
public class RootObject {
public IDictionary<string, int[]> pickups { get; set; }
}
This is what son2csharp.com says, its gets error because you can not define names with starting number. 这就是son2csharp.com所说的,它出错,因为您无法用开始编号定义名称。
public class Pickups
{
public List<int> __invalid_name__7 { get; set; }
public List<int> __invalid_name__10 { get; set; }
public List<int> __invalid_name__15 { get; set; }
public List<int> __invalid_name__20 { get; set; }
public List<int> __invalid_name__25 { get; set; }
}
public class RootObject
{
public Pickups pickups { get; set; }
}
But I think 但我觉得
[DataMember(Name = "Name")]
should work cause its not an error in JSON format side. 应该工作,因为它不是JSON格式的错误。
If it is a viable option for you to use JObject.Parse(...) instead, you could use the following code (and write it more cleanly, with exception handling and safe casts and so on): 如果对您来说,使用JObject.Parse(...)是一个可行的选择,则可以使用以下代码(并使用异常处理和安全强制转换等将其编写得更干净):
var jsonPickups = JObject.Parse(json);
var myPickups = new Pickups
{
pickups = jsonPickups.First.First.Select(x =>
{
JProperty xProp = x as JProperty;
return new Pickup
{
Group = int.Parse(xProp.Name),
Values = (xProp.Value as JArray).Select(y => int.Parse(y.ToString())).ToArray()
};
}).ToArray()
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.