如何将Json表(数组数组)数据转换为c#对象的集合

时间:2015-08-22 03:22:02

标签: c# json json.net

我有一个像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);

列映射将根据值的顺序保持一致。

修改

我希望以类似于此示例的更友好的方式获取数据:

{
    "Data": [
        {
            "column name 1": "blah bla"
        },
        {
            "column name 1": "T"
        },
        {
            "column name 1": "blahbla"
        }
    ]
}

但是我不能控制它......

1 个答案:

答案 0 :(得分:2)

您可以使用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