Newtonsoft反序列化Array以使用属性进行分类 [英] Newtonsoft deserialize Array to class with properties
问题描述
使用外部服务时,他们决定提供一个对象作为数组,其中每个属性都位于固定位置.喜欢
Consuming an external service where they decided to provide an object as an array where each property is on a fixed position. Like
{
"persons" : [
["Luck", "Lucky", 28],
["Joe", "Dalton", 30],
["Jack", "Dalton", 28],
["William", "Dalton", 26],
["Averell", "Dalton", 24]
]
}
我想将其反序列化为人员列表".
I would like to deserialize this to a List of Person.
var persons = JsonConvert.DeserializeObject<Person[]>(json);
class Person {
public string FirstName {get; set; }
public string LastName {get; set; }
public int Age{get; set; }
}
是否有一种简单的方法(属性注释)来执行此操作,还是会写一个自定义序列化程序?
Is there an easy way (property annotation) to do this, or will it come down to write a custom serialiser?
由于大多数答案都缺少问题的实质.
Since most answers are missing the essence of the question.
如果这很容易
{
"persons" : [
{
"FirstName" : "Luck",
"LastName" : "Lucky",
"Age" : 28
},
// ...
]
}
但事实并非如此.
推荐答案
persons
属性是字符串数组的数组.尝试先反序列化为List<List<string>>
persons
property is array of arrays of strings. Try to deserialize to List<List<string>>
first
public class Root
{
public List<List<string>> persons { get; set; }
}
,然后使用Select
方法
and then convert it to list of List<Person>
using Select
method
var root = JsonConvert.DeserializeObject<Root>(jsonString);
var persons = root.persons
.Select(l => new Person { FirstName = l[0], LastName = l[1], Age = int.Parse(l[2]) })
.ToList();
这篇关于Newtonsoft反序列化Array以使用属性进行分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!