C#客户端Json转DataTable | 您所在的位置:网站首页 › JSON转化为db › C#客户端Json转DataTable |
本文转自 https://blog.csdn.net/pinebud55/article/details/52240287 感谢pinebud55分享 之前我们有讨论过c#是如何处理json的,在我的客户端中,需要接收服务端的数据,并且用列表展示出来,列表控件我采用的是winfrom自带的DataGridView,从服务端得到的响应是一串json字符串,为了提高效率和简洁代码,我不想采用解析json并填充控件的方式,而是希望将json转化为datatable,直接绑定控件. 解决方案解析Json.我们从服务端得到的json格式如下 string response={"672": {"id": "672", "level":0, "children":[ "b9185a050d0540fea32cdd6fdf5e0d7d", "727dc5216f504174a30475f268a616f8", "57c8e7da25a34bee832d8fd2cfeed5c1"] }, "673": {"id": "673", "level":1, "children":[ "b9185a050d0540fea32cdd6fdf5e0d7d", "727dc5216f504174a30475f268a616f8", "57c8e7da25a34bee832d8fd2cfeed5c1"] } }参考之前文字的解析,将字符串转换为Json对象,之后转换为JProperty对象,方便之后遍历 JObject json = JObject.Parse(response); IEnumerable property = json.Properties();2.转换为JArray对象 JObject和JProperty对象均不能转换为datatable,只有JArray可以,所以通过遍历将JProperty对象转换为JArray。 JArray ay = new JArray(); foreach (JProperty item in property) { JObject child = JObject.Parse(item.Value.ToString()); ay.Add(child); }3.反序列化Json 得到的JArray对象实际上是一个Json的字符串数组,我们将其进行反序列化 DataTable db=new DataTable(); db=JsonConvert.DeserializeObject(ay.ToString());完整代码如下: JObject json = JObject.Parse(response); IEnumerable property = json.Properties(); JArray ay = new JArray(); DataTable db=new DataTable(); foreach (JProperty item in property) { JObject child = JObject.Parse(item.Value.ToString()); ay.Add(child); } db=JsonConvert.DeserializeObject(ay.ToString()); dataGridView1.DataSource = db;当然,也可以将datatable 对象序列化为Json string json = JsonConvert.SerializeObject(dt);
|
CopyRight 2018-2019 实验室设备网 版权所有 |