在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中所攜帶的值。
//mc21v if (mc21v != null && mc21v["tree"] != null && mc21v["tree"][0]["tree"] != null && mc21v["tree"][0]["tree"].Count() > 0) { var name = mc21v["tree"][0]["name"].ToString(); var submc21v = mc21v["tree"][0]["tree"]; foreach (var s in submc21v) { log.LogInformation(name + " / " + s["name"].ToString()); } }
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 *