Confucius said, "if you want to do well, you must sharpen your tools first."
github address: https://github.com/redAntCpp/CSharpTools
When dealing with web requests, it is inevitable to deal with data. The common data interaction methods are XML and JSON. In C #, XML has systematic help classes, so records are no longer described. Here I share a JSON constructor class written by myself.
For an introduction to json, please refer to: https://www.w3school.com.cn/js/js_json_intro.asp
The essence of JSON is a string, which is combined according to certain rules (next, assume that all transmitted contents are strings). We can follow this idea and split the structure of JSON.
Suppose our goal is to assemble such a json:
{ "companyID": "15", "employees": [{ "firstName": "Bill", "lastName": "Gates" }, { "firstName": "123", "lastName": "Bush" }], "manager": [{ "salary": "6000", "age": "23" }, { "salary": "8000", "age": "26", "cars": ["Porsche", "BMW", "Volvo"] }], "cc": { "salary": "test", "age": "100" }
Simple Json element
JSON elements can be divided into two parts: key and value. Together:
"key":"value"
Therefore, a json element class must have two elements:
class JsonElement { private string JValue; private string JsonKey = ""; }
Then, in the constructor, splice out our json elements:
public JsonElement(string key, string value) { this.Jkey = key; this.jsonValue = value; JElement = string.Format("\"{0}\":\"" + JValue + "\"", Jkey); }
Finally, use innertext to output the contents of the structure:
public string innerText { get { return this.tostring(); } } public string tostring() { return JElement; }
After processing, we get the element structure as "key": "value". Completed the first step.
Simple Json document
In the general appearance of json, we choose a simple purpose to form a simple json document:
{ "firstName": "132", "lastName": "Bush" }
A simple json document can be composed of closed single parentheses and multiple json elements, so we can do this by creating a new json document class with multiple json elements separated by commas and encapsulated in the add method:
class JsonDocument { string JDocument; public JsonDocument() { this.JDocument = ""; } public void add(JsonElement je) { if (JDocument == "") { this.JDocument = je.innerText; } else { this.JDocument = JDocument + "," + je.innerText; } } }
The final json document needs single parentheses, so we add it when we output the content
private string tostring() { return "{" + JDocument + "}"; }
Simple Json object
Let's start with a simple json object
"cc": { "salary": "test", "age": "100" }
Compared with a simple json document, there is an additional key here, so we can add this key to a json document to generate such an object:
class JsonObject { private string JObjectValue; private string Jkey; public JsonObject(string key,JsonDocument jd) { this.Jsonkey = key; this.innerText = jd.innerText; } }
Simple Json array
First look at a simple JSON array:
["Porsche", "BMW", "Volvo"]
We usually don't take the key with us. Become a simple json object. Due to the trivial use, this definition is not implemented in JOSN objects.
We can see the difference between json arrays:
- Package with [] instead of {}.
- It can be a pure string, not necessarily a pure json document or json element.
- A variety of different data structures can be installed.
- Therefore, we need to consider the loading of different data structures. Therefore, it is implemented with the help of container list < T >.
//Constructor "key":[value1,value2...] public JsonArray(string key, string[] ValueList) { this.Jkey = key; JstrArryList = new List<string>(ValueList);//Convert array to list } //Constructor "key":[josn1,json2...] public JsonArray(string key, JsonDocument[] ValueList) { this.Jkey = key; JArryList = new List<JsonDocument>(ValueList); } public JsonArray(string key) { this.Jkey = key; JArryList = new List<JsonDocument>(); JstrArryList = new List<string>(); } public JsonArray() { this.Jkey = ""; JArryList = new List<JsonDocument>(); JstrArryList = new List<string>(); }
When outputting, traverse the elements in the list and output them one by one:
public string tostring() { string StrValueList = ""; //Output json object if (JArryList != null && JArryList.Count != 0)//Exists and the number of elements is 0 { for (int i = 0; i < JArryList.Count; i++) { StrValueList = StrValueList + JArryList[i].innerText + ","; } StrValueList = StrValueList.Remove(StrValueList.Length - 1, 1); } else if (JstrArryList != null && JstrArryList.Count != 0) //Output json array string { for (int i = 0; i < JstrArryList.Count; i++) { StrValueList = StrValueList + "\"" + JstrArryList[i] + "\"" + ","; } StrValueList = StrValueList.Remove(StrValueList.Length - 1, 1); } else { StrValueList = ""; } //Separate analysis StrValueList = "[" + StrValueList + "]"; //At 20:53:25 on January 23, 2022, the key in the new array is empty if (Jkey == "") { return StrValueList; } else { string temp = string.Format("\"{0}\":", Jkey); StrValueList = temp + StrValueList; return StrValueList; } }
Assemble complex JSON
Now use the class just written to assemble the JSON mentioned at the beginning:
private void button5_Click(object sender, EventArgs e) { //1. Create a json element JsonElement companyID = new JsonElement("companyID", "15"); JsonArray employeesArry = new JsonArray("employees"); JsonDocument employeesdoc1 = new JsonDocument(); employeesdoc1.add(new JsonElement("firstName", "Bill")); employeesdoc1.add(new JsonElement("lastName", "Gates")); JsonDocument employeesdoc2 = new JsonDocument(); employeesdoc2.add(new JsonElement("firstName", "")); employeesdoc2.add(new JsonElement("lastName", "Bush")); employeesArry.add(employeesdoc1); employeesArry.add(employeesdoc2); JsonArray manager = new JsonArray("manager"); JsonDocument manager1 = new JsonDocument(); manager1.add(new JsonElement("salary", "6000")); manager1.add(new JsonElement("age", "23")); string[] carslist = { "Porsche", "BMW", "Volvo" }; JsonArray cars = new JsonArray("cars", carslist); JsonDocument manager2 = new JsonDocument(); manager2.add(new JsonElement("salary", "8000")); manager2.add(new JsonElement("age", "26")); manager2.add(cars); manager.add(manager1); manager.add(manager2); JsonDocument cc_txt = new JsonDocument(); cc_txt.add(new JsonElement("salary", "test")); cc_txt.add(new JsonElement("age", "100")); JsonObject jo = new JsonObject("cc", cc_txt); //Assemble the overall document JsonDocument jd = new JsonDocument(); jd.add(companyID); jd.add(employeesArry); jd.add(manager); jd.add(jo); //Output document textBox1.Text = jd.innerText; }
The code is a little long, but the idea is very clear. Usually, the json we encounter will not be so complex. It is very good as a tool to record the process.