如何将json单个键/值对转换为DataTable?

时间:2015-07-27 07:35:02

标签: c# json datatable

我有一个json字符串,其中包含键/值对。现在,我想将key/value对转换为DataTable Columns (key,value)

以下是json字符串:

{  
   "wifi_result":"1",
   "mic_result":"1",
   "video_result":"1",
   "touch_result":"1",
   "proximity_result":"1",
   "vibrator_result":"1",
   "power_key":"2",
   "accelerometer":"0",
   "earphone":"1",
   "memory_result":"1",
   "memory_internalSD":"1",
   "memory_internalSDSize":"25.0GB",
   "memory_externalSD":"0",
   "memory_externalSDSize":"",
   "memory_internalflash":"1",
   "memory_internalflashSize":"2.0GB",
   "memory_ram":"1",
   "memory_ramsize":"2.0GB",
   "lcd_result":"1",
   "lcd_broken":"1",
   "key_result":"1",
   "vol_key_up":"1",
   "vol_key_down":"0",
   "menu_key":"1",
   "headset_result":"1",
   "headset_leftearphone":"1",
   "headset_rightearphone":"0",
   "camera_result":"1",
   "camera_cameracount":"1",
   "camera_frontcam":"0",
   "camera_backcam":"0",
   "battery_result":"1",
   "battery_type":"1",
   "battery_level":"83",
   "battery_status":"1",
   "battery_voltage":"4204",
   "battery_temperature":"310",
   "battery_accharging":"0",
   "battery_usbcharging":"1",
   "audio_result":"1",
   "home_key":"1",
   "back_key":"1"
}

必填项:

DataTable行必须是:

Key          |  Value
wifi_result  |    1
mic_result   |    1

帮助表示赞赏!

2 个答案:

答案 0 :(得分:3)

您不需要DataTable。实际上,它是Dictionary<string,string>

使用Json.Net

var  dict = JsonConvert.DeserializeObject<Dictionary<string,string>>(json);

现在您拥有键/值对。

如果必须使用DataTable,那么

var dt = JArray.FromObject(dict.Select(x => x)).ToObject<DataTable>();

答案 1 :(得分:0)

您可以先将反序列化为c#类,然后将其转换为数据表。

OR

可以使用JSON.NET直接转到数据表 实施例 - :

DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));