我有一个json格式的表(数组的数组)对象,我想转换为c#对象的集合。
{
"Columns": [
{
"id": 1,
"name": "column name 1",
"other stuff": "blah blah"
},
{
"id": 2,
"name": "column name 2",
"other stuff": "blah blah"
},
{
"id": 3,
"name": "column name 3",
"other stuff": "blah blah"
}
],
"Data": [
[
"blah bla",
"bloop",
1
],
[
"t",
"another random value",
5
],
[
"foo",
"bar",
5
],
[
"something valuable",
"value2",
5
]
]
}
我想把它序列化成一个对象或数据表的集合,如下所示:
public class Row
{
public string ColumnName1 {get;set;}
public string ColumnName2 {get;set;}
public int ColumnName3 {get;set;}
}
var jsonString = "same as above just properly escaped";
list<Row> rows = Deserialize(jsonString);
列映射将根据值的顺序保持一致。
编辑:我希望有一个更c#友好的方式的数据类似于这个例子:
{
"Data": [
{
"column name 1": "blah bla"
},
{
"column name 1": "T"
},
{
"column name 1": "blahbla"
}
]
}
但是我不能控制这个,所以。
可以使用Json。. Net的LINQ-to-JSON API将JSON数据解析成您想要的格式:
JObject jo = JObject.Parse(json);
List<Row> rows = jo["Data"]
.Children<JArray>()
.Select(ja => new Row
{
ColumnName1 = (string)ja[0],
ColumnName2 = (string)ja[1],
ColumnName3 = (int)ja[2]
})
.ToList();
小提琴:https://dotnetfiddle.net/bA9vSH