如何将json单键/值对转换为数据表
本文关键字:转换 数据表 json 单键 | 更新日期: 2023-09-27 18:04:44
我有一个包含键/值对的json
字符串。现在,我想用Columns
(key,value)
将key/value
对转化为DataTable
以下是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
帮助感激!
对此不需要DataTable。事实上,它是一个Dictionary<string,string>
使用Json。净
var dict = JsonConvert.DeserializeObject<Dictionary<string,string>>(json);
现在你有键/值对了。
如果DataTable是必须的,那么
var dt = JArray.FromObject(dict.Select(x => x)).ToObject<DataTable>();
您可以先反序列化为c#类,然后将其转换为数据表。
或
可以使用JSON直接访问数据表。网外:
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));