在C#中解析JSON的一些历史代码记录,分别记录针对各种情况的解析方式。
DLL的引用
using Newtonsoft.Json; using Newtonsoft.Json.Linq;
需要使用的类型
JArray:对应JSON字符串中的[]数组表示
JArray x = JArray.Parse(jsonresult); x[0].ToString()//或在知晓JSON格式的对象时,可直接反序列化。JsonConvert.DeserializeObject<List<T>>(jsonresult);
JObject:对应JSON字符串中的{"key":"value"}对象键值对
JObject obj = JObject.Parse(jsoncontent); obj ["Key Name"].ToString()//或在知晓JSON格式的对象时,可直接反序列化。JsonConvert.DeserializeObject<T>(jsoncontent);
JToken:针对JSON中的值为["value1","value2","value3"]的情况使用JToekn解析后,可以直接使用jtoken[i]依次获取value
JToken jtvalue= JToken.Parse(jsonstring); jtvalue[0].ToString()
JSON字符串格式一:
[ { "tree": [ { "id": "b661f9c2-28ee-800a-b621-118a6787a8e6", "name": "Automanage Preview", "type": "productname", "tree": [ { "id": "d2067d69-7bb0-9ee4-cdf8-097211d4229a", "tree": [ { "id": "647d2678-3991-b6f2-595c-5215afaaa61a", "type": "category", "typeid": "bcc1837c-6364-a038-6359-afaa3b5144b5", "tags": [] }, { "id": "cf520d66-1d51-3644-2d60-f26a2ce384c3", "name": "Can't create", "type": "category", "typeid": "5414a0bd-ea3d-77f1-2bed-07800e2c7e32", "state": "public", "tags": [] }, { "id": "8279780f-d659-5819-0598-f9cca054d8df", "name": "Error when ", "type": "category", "typeid": "6c35e082-3d87-83d4-9fa7-d213a2e998b3", "state": "public", "tags": [] },
使用JArray来解析JSON字符串到由JSON Object组成的数组,也可以通过Linq语句来过滤。
JArray x = JArray.Parse(result); var mc21v = x.Children<JObject>().FirstOrDefault(o => o["tree"][0]["name"] != null && o["tree"][0]["name"].ToString() == "filter value");
通过对象中的tree ->name查找JSON字符串中高亮部分,也是第一级Tree节点下子节点的name来过滤。当获取到mc21v 节点对象后,继续根据是否由数组,是否是对象(由key存在)依次递归来获取JSON中所携带的值。
C# 自动换行 xxxxxxxxxx 3 1 JArray x = JArray.Parse(result); 2 3 var mc21v = x.Children<JObject>().FirstOrDefault(o => o["tree"][0]["name"] != null && o["tree"][0]["name"].ToString() == "filter value"); 为卡片添加间距 删除卡片
JSON字符串格式二:
{ "table_parameters": [ { "header_names": [ "ID", "Name", "Time", ... ], "table_parameter_result": [ [ "3125649", "test", "2020-10-23T18:35:52.4121265", ..... ], [ "123123545", "test again", "2020-10-23T20:27:27.3168876", ... ], [ "120100503",
以上格式为自定义的JSON表格格式,table_parameters节点中包含表头(header_names)和表内容(table_parameter_result),所以在获取值时候,就需要使用到JArray和JToken。
JObject details = JObject.Parse(sdresult); JToken resultTableObj = details["table_parameters"][0]; resultTableObj[i].ToString()
附加一:使用Python读取JSON格式得文件内容并输出
import os, uuid import json try: local_path = "." local_file_name = "All My Case.json" upload_file_path = os.path.join(local_path, local_file_name) with open(upload_file_path, "r") as data: #print(data.read()) y = json.loads(data.read()) print(len(y)) for c in y: print(c[0]+","+c[8]+","+c[36]+","+c[42]) except Exception as ex: print('Exception:') print(ex)
What is JSON?
- JSON stands for JavaScript Object Notation
- JSON is a lightweight data-interchange format
- JSON is "self-describing" and easy to understand
- JSON is language independent *