将json respone转换为datatable

时间:2018-01-19 13:01:11

标签: c# arrays json

我有来自API的json响应,我需要将该信息存储在数据表中。响应类似于:

{
    "columns": [ 
      "firstName", 
      "lastName", 
      "email", 
      "password",
    ],
    "rows": [
      [
        "Alpha",
        "Tango",
        "AlphaTango@domain.com",
        "123"
      ],
      [
        "Charle",
        "Tango",
        "CharlieTango@domain.com",
        "456"
      ]
    ]
}

我需要将其转换为以下格式:

firstName lastName email                   password
Alpha     Tango    AlphaTango@domain.com   123
Charle    Tango    CharlieTango@domain.com 456

我在下面的代码片段的帮助下反过来了,但是我无法将json转换回数据表可接受的格式:

JsonConvert.SerializeObject(new {
   columns = dt1.Columns.Cast<DataColumn>().Select(x => x.ColumnName),
   rows = dt1.AsEnumerable().Select(r => r.ItemArray),
});

任何建议或指示都将受到高度赞赏

1 个答案:

答案 0 :(得分:1)

对于这种情况,您必须对json数据进行一些手动迭代。你能试试下面的代码吗?

static void Main(string[] args)
{
    string json = "{\"columns\":[\"firstName\",\"lastName\",\"email\",\"password\",],\"rows\":[[\"Alpha\",\"Tango\",\"AlphaTango@domain.com\",\"123\"],[\"Charle\",\"Tango\",\"CharlieTango@domain.com\",\"456\"]]}";
    dynamic jObject = JObject.Parse(json);
    //Get columns of your object
    List<string> columns = JsonConvert.DeserializeObject<List<string>>(jObject.columns.ToString());
    //Get rows of your object
    List<string[]> rows = JsonConvert.DeserializeObject<List<string[]>>(jObject.rows.ToString());

    using (DataTable dt = new DataTable())
    {
        //Create columns
        foreach (string column in columns)
            dt.Columns.Add(new DataColumn(column));

        //Add rows
        foreach (string[] row in rows)
        {
            int columnOrdinal = 0;
            DataRow newRow = dt.NewRow();
            foreach (string value in row)
            {
                newRow.SetField<string>(columnOrdinal, value);
                columnOrdinal++;
            }
            dt.Rows.Add(newRow);
        }

    }
}

以上代码的结果: Result for the code above

希望这有帮助