Why do you need a new JSON API?
JSON.NET Everybody used it. The old version ASP.NET Core also relies on JSON.NET 。
However, this dependency can cause some version problems: for example, one version of ASP. Net core needs to use JSON. Net V10, while another library needs to use it JSON.NET V11; or there is a new version of JSON. Net that ASP. Net core does not support, and you want to use it.
With the appearance of net core 3.0, system appeared Text.Json The namespace and some of the classes below it are used to handle JSON.
This built-in JSON API has inherent high-performance, distributed features:
JSON. Net uses the string in. Net as the basic data type, which is actually utf16, while the new JSON API in. Net core directly uses the original utf8 format of data.
The new JSON API is based on the data type span < byte > to operate JSON data, so it has the characteristics of low allocation, which can greatly improve the throughput and memory usage.
However, the features of the new JSON API are not so rich, and some features of JSON. Net are not supported yet.
I randomly found a JSON sample file:
For this file, you need to modify its properties:
First use the utf8jsonreader to read the JSON file.
Utf8jsonreader does not read files or streams, it does read span data types.
In the main method, we use file. Readallbytes to read the data from the sample. JSON file in byte  format, and then convert it to the span < byte > data type through the asspan extension method, and then pass it to the constructor of utf8jsonreader to create a JSON reader.
Next, use the while loop to read each token of the JSON data. Each time the read() method is executed, the reader will move to the next token in the JSON data.
Token is divided into several types. The gettoken info method is to judge the type of token and return some descriptive information, which should contain all types. The switch expression of C ා 8 is used here.
Run the program
The results were as follows:
You can see sample.json Each token in the file is displayed correctly.
JSON document class
JSON document is built based on utf8jsonreader. Jsondocument can analyze JSON data and generate a read-only document object model (DOM). It can query the model to support random access and enumeration. Use jsondocument to analyze a regular JSON payload and access all its members Json.NET It is 2-3 times faster and has very little allocated for data of reasonable size (i.e. < 1 MB).
Jsondocument can handle span and stream.
Here, I use file. Openread to convert JSON files to streams. Then use Jason Document.Parse Method to parse stream into JSON document object model.
I’ll use the syntax of Ŧ var.
Next, we start to traverse from the root node of the JSON document object model, that is, rootelement:
Then get the corresponding properties through the getproperty method of the jsonelement type object root, and this method can be used in series:
The last line uses the getString method to get the string value of the property.
Then we can write a recursively called method to traverse each property of the whole model:
This method takes an object of type jsonelement and loops through the attributes of that element.
If the current property is another object, the method is called recursively;
Otherwise, the original text is output.
Finally, the method is called:
The output results are as follows:
Matches the contents of the JSON file.
Let’s look at how to write a JSON file. You need to use the UTF 8jsonwriter class here.
Look directly at the code:
The parameter type that this class needs to pass is stream or buffer, that is to write data to stream or buffer.
A buffer is provided
Here is a separate method to generate JSON data:
The parameter type is UTF 8jsonwriter. You can see from the smart prompt that it provides many methods for writing different types of data.
Writing JSON objects
Now I want to write a JSON object. Start with write startobject() and end with writeend object():
In this case, I actually have a legitimate JSON document.
Write properties and values
You can write properties and values separately:
You can also write the attributes and values at the same time:
Display JSON data
I first write these contents, and then call them in the main method:
First of all, we need to tell the writer to flush its contents to the buffer. With this buffer, we can get the output of the writer. In this way, we will get a byte array, and then convert the byte array into a string. In this way, we can display it on the console
Run it to see the effect:
There’s no big problem, just the format is not good.
Format the output
The. Net core provides a jsonwrite r options class, which can make some settings on the writer.
The output is indented here, and the options are passed to the constructor of UTF 8jsonwriter.
It’s much better now.
The contents of the previous sections may be a little bit low-level. Most of the time, we only need to serialize the C ා class or deserialize the JSON data into C ා class. In. Net core 3.0, we can use the jsonserializer class to do these things.
Or use the previous JSON data:
Then we need to create two classes corresponding to this file:
You can use the deserialize() method of the JSON serializer class to deserialize JSON data. This method supports three types of input parameters, namely:
- String of JSON data
- Utf 8JsonReader
- Read onlyspan < byte >, which contains JSON data
For simplicity, I directly read the JSON file into a string, and then pass it to the deserialize method:
Then I tried to print out some attribute data after deserialization. But it won’t work. Because the case naming standard of data in JSON file uses camel casting (the first letter is lowercase). By default, deserializer will look for the attribute name of Pascal casting (simply understood as the first letter of each word is uppercase).
To solve this problem, you need to use the jsonserializerpoptions class:
Create an instance of this class, set property naming policy to camelCase, and pass this instance to the second parameter of the deserialize method.
The results are as follows:
There will be no problem this time.
JSON serializer also supports serialization, that is to convert C ා data into JSON data
The same options are used here.
If you want to make the output more beautiful, you can set the corresponding settings in jsonserializer options
The output results are as follows:
To summarize the new JSON API for. Net core 3.0:
- UTF 8jsonreader – read operation, fast, low level
- UTF 8jsonwriter – write operation, fast, low level
- Jsondocument – dom based, fast
- Johnson seriliazer – serialization / deserialization, fast
In addition, JSON. Net is still supported.
This article about the detailed explanation of the new JSON API in. Net core 3.0 will introduce here. For more related. Net core 3.0 JSON content, please search the previous articles of developeppaer or continue to browse the related articles below. I hope you can support developeppaer more in the future!