Newtonsoft.Json
Newtonsoft.Json is a tool for manipulating JSON on the .Net platform. There is no need to elaborate on its introduction; I have recently been working on interfaces that require JSON manipulation.
Taking the Token from a certain cloud computing platform as an example, I will explain while demonstrating the operations.
Json to Model
Convert Model to Json
Convert LINQ to JSON
LINQ Operations
Namespace, Types, and Methods Collection
Additionally, here is the Baidu AI Text Recognition Json and its Model Class
Newtonsoft.Json converts strings to objects based on type object names, case insensitively, but the names must be consistent, even if your JSON only contains one entry.
{ "a":1}
Your object
public class Test { public int aa{get;set;} }
It also cannot correspond.
For complex hierarchical JSON, you can use “nested classes” to map them, and be mindful of the use of List<T>/Array/ArrayList types.
Json to Model
Create a new Json file, with a name of your choice, for example json1.json
Paste the following content into it
{ "refresh_token": "25.ea2f85ebd48df85fe5400000.18640.282335-15533349", "expires_in": 2592010, "session_key": "9mzdWr3n8ncMeDgX8zjhkhlW8khb5cdZtPevPbPwQGBg==", "access_token": "24.ac0ca9fakhlkyhl552017858.282335-15533349", "scope": "audio_voice_assistant_get audio_tts_post public vis-ocr_ocr nlp_simnet nlp_wclassify_watermark brain_ocr_scope vis-classify_car brain_gif_antiporn brain_ocr_general brain_ocr_general_basic brain_ocr_generer vis-classify_animal brain_politician brain_unit_utterance brain_imgquality_general brain_nlp_simnet brain_nlp_depparser vis-classify_plant brain_solution brain_ocr_plate_number brain_nlp_wordembedding brain_nlp_dnnlm_cn_legacy brain_nlp_simnet_legacy brain_nlp_commain_animal_classify brain_plant_classify brain_solution_iocr brain_realtime_product brain_nlp_lexer_custom brain_kgbody_analysis brain_body_attr brain_ocr_vat_invoice brain_advanced_general_classify brain_numbers brain_body_number vis-faceverify_FACE_auth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi", "session_secret": "2ca66d464545c77a4767f709873be4" }
Define a model with the filename AccessTokenModel.cs
public class AccessTokenModel { public string refresh_token { get; set; } public string expires_in { get; set; }//: Validity period of Access Token (in seconds, generally 1 month) public string scope { get; set; } public string session_key { get; set; } public string access_token { get; set; }//: Access Token to be obtained public string session_secret { get; set; } }
Open the Program.cs file
public static void Main(string[] args) { FileStream fs = new FileStream(@"Please change to your file path\json1.json", FileMode.Open); StreamReader fileStream = new StreamReader(fs); string str = ""; string line; while ((line = fileStream.ReadLine()) != null) { str += line; }
// The above code has no effect, it simply loads the contents of the JSON file into a string
JObject jObject = new JObject(); // Create the operation object AccessTokenModel a = JsonConvert.DeserializeObject<AccessTokenModel>(str);Console.WriteLine(<strong>a.access_token</strong>); // Output a property at random Console.ReadKey(); }</span></pre>
Key method
JsonConvert.DeserializeObject<the model class to convert>("string object");
After this, the contents of the JSON file can be easily stored in a database.
Collection
Change the Json file to the following format
[{ "refresh_token": "25.ea2f85ebd48df85fe5400000.18640.282335-15533349", "expires_in": 2592010, "session_key": "9mzdWr3n8ncMeDgX8zjhkhlW8khb5cdZtPevPbPwQGBg==", "access_token": "24.ac0ca9fakhlkyhl552017858.282335-15533349", "scope": "audio_voice_assistant_get audio_tts_post public vis-ocr_ocr nlp_simnet nlp_wclassify_watermark brain_ocr_scope vis-classify_car brain_gif_antiporn brain_ocr_general brain_ocr_general_basic brain_ocr_generer vis-classify_animal brain_politician brain_unit_utterance brain_imgquality_general brain_nlp_simnet brain_nlp_depparser vis-classify_plant brain_solution brain_ocr_plate_number brain_nlp_wordembedding brain_nlp_dnnlm_cn_legacy brain_nlp_simnet_legacy brain_nlp_commain_animal_classify brain_plant_classify brain_solution_iocr brain_realtime_product brain_nlp_lexer_custom brain_kgbody_analysis brain_body_attr brain_ocr_vat_invoice brain_advanced_general_classify brain_numbers brain_body_number vis-faceverify_FACE_auth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi", "session_secret": "2ca66d464545c77a4767f709873be4" }, { "refresh_token": "25.ea2f85ebd48df85fe5400000.18640.282335-15533349", "expires_in": 2592010, "session_key": "9mzdWr3n8ncMeDgX8zjhkhlW8khb5cdZtPevPbPwQGBg==", "access_token": "24.ac0ca9fakhlkyhl552017858.282335-15533349", "scope": "audio_voice_assistant_get audio_tts_post public vis-ocr_ocr nlp_simnet nlp_wclassify_watermark brain_ocr_scope vis-classify_car brain_gif_antiporn brain_ocr_general brain_ocr_general_basic brain_ocr_generer vis-classify_animal brain_politician brain_unit_utterance brain_imgquality_general brain_nlp_simnet brain_nlp_depparser vis-classify_plant brain_solution brain_ocr_plate_number brain_nlp_wordembedding brain_nlp_dnnlm_cn_legacy brain_nlp_simnet_legacy brain_nlp_commain_animal_classify brain_plant_classify brain_solution_iocr brain_realtime_product brain_nlp_lexer_custom brain_kgbody_analysis brain_body_attr brain_ocr_vat_invoice brain_advanced_general_classify brain_numbers brain_body_number vis-faceverify_FACE_auth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi", "session_secret": "2ca66d464545c77a4767f709873be4" } ]
public static void Main(string[] args) { FileStream fs = new FileStream(@"请修改成你的文件路径\json1.json", FileMode.Open); StreamReader fileStream = new StreamReader(fs); string str = ""; string line; while ((line = fileStream.ReadLine()) != null) { str += line; } // The above code is meaningless, it just loads the content of the Json file into a string JObject jObject = new JObject(); // Create a new operation object List<AccessTokenModel> a = JsonConvert.DeserializeObject<List<AccessTokenModel>>(str); foreach (var i in a) { Console.WriteLine(i.access_token); }Console.ReadKey(); }</pre>
Convert Model to Json
Can convert model objects to Json.
Continue using the above AccessTokenModel.cs file,
public static void Main(string[] args) { AccessTokenModel accessTokenModel = new AccessTokenModel(); accessTokenModel.access_token = "test1"; accessTokenModel.expires_in = "test2"; accessTokenModel.refresh_token = "test3"; accessTokenModel.scope = "test4"; accessTokenModel.session_key = "test5"; accessTokenModel.session_secret = "test6";JObject jObject = new JObject(); string str = JsonConvert.SerializeObject(accessTokenModel); // Convert to string Console.WriteLine(str); Console.ReadKey(); }</pre>
Key method
JsonConvert.SerializeObject(model object);
After running, you can see that the console output is the Json string, and you can continue to place it into a Json file; it will not be elaborated here.
Convert LINQ to JSON
This example is directly copied from the official website, Jarray is a type provided by its framework.
After running in the console, you will find that the output characters are already formatted
。
public static void Main(string[] args) { JArray array = new JArray(); array.Add("Manual text"); array.Add(new DateTime(2000, 5, 23));JObject o </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> JObject(); o[</span><span style="color: #800000;">"</span><span style="color: #800000;">MyArray</span><span style="color: #800000;">"</span>] =<span style="color: #000000;"> array; </span><span style="color: #0000ff;">string</span> json =<span style="color: #000000;"> o.ToString(); </span><span style="color: #008000;">//</span><span style="color: #008000;"> { </span><span style="color: #008000;">//</span><span style="color: #008000;"> "MyArray": [ </span><span style="color: #008000;">//</span><span style="color: #008000;"> "Manual text", </span><span style="color: #008000;">//</span><span style="color: #008000;"> "2000-05-23T00:00:00" </span><span style="color: #008000;">//</span><span style="color: #008000;"> ] </span><span style="color: #008000;">//</span><span style="color: #008000;"> }</span>
Console.WriteLine(json);
Console.ReadKey();
Linq Operations
The framework provides support for Linq operations on JObject objects.
using Newtonsoft.Json.Linq;
After that, you can work with it as conveniently as you would with arrays, collections, or Contexts.
Namespaces, Types, and Methods Overview
I initially intended to provide a translation for this, but my English is not good enough, so let's skip it.
Classes:
| Class | Description |
|-------|-------------|
| DefaultJsonNameTable |
|
| JsonArrayAttribute |
|
| JsonConstructorAttribute |
|
| JsonContainerAttribute |
|
| JsonConvert |
|
| JsonConverter |
|
| JsonConverter<T> |
|
| JsonConverterAttribute |
|
| JsonConverterCollection |
|
| JsonDictionaryAttribute |
|
| JsonException |
|
| JsonExtensionDataAttribute |
|
| JsonIgnoreAttribute |
|
| JsonNameTable |
|
| JsonObjectAttribute |
|
| JsonPropertyAttribute |
|
| JsonReader |
|
| JsonReaderException |
|
| JsonRequiredAttribute |
|
| JsonSerializationException |
|
| JsonSerializer |
|
| JsonSerializerSettings |
|
ewtonsoft_Json_JsonSerializer.htm">JsonSerializer</a> object.</div>
</td>
</tr>
<tr>
<td><img title="Public class" src="https://www.newtonsoft.com/json/help/icons/pubclass.gif" alt="Public class" /></td>
<td><strong><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonTextReader.htm">JsonTextReader</a></strong></td>
<td>
<div class="summary">Represents a reader that provides fast, non-cached, forward-only access to JSON text data.</div>
</td>
</tr>
<tr>
<td><img title="Public class" src="https://www.newtonsoft.com/json/help/icons/pubclass.gif" alt="Public class" /></td>
<td><strong><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonTextWriter.htm">JsonTextWriter</a></strong></td>
<td>
<div class="summary">Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.</div>
</td>
</tr>
<tr>
<td><img title="Public class" src="https://www.newtonsoft.com/json/help/icons/pubclass.gif" alt="Public class" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonValidatingReader.htm">JsonValidatingReader</a></td>
<td><strong>Obsolete.</strong>
<div class="summary">
<p>Represents a reader that provides <a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Schema_JsonSchema.htm">JsonSchema</a> validation.</p>
<div class="alert">
<table>
<tbody>
<tr><th><img src="https://www.newtonsoft.com/json/help/icons/AlertCaution.png" alt="Caution note" /> Caution</th></tr>
<tr>
<td>JSON Schema validation has been moved to its own package. See <a href="https://www.newtonsoft.com/jsonschema" target="_blank" rel="noopener noreferrer">https://www.newtonsoft.com/jsonschema</a> for more details.</td>
</tr>
</tbody>
</table>
</div>
</div>
</td>
</tr>
<tr>
<td><img title="Public class" src="https://www.newtonsoft.com/json/help/icons/pubclass.gif" alt="Public class" /></td>
<td><strong><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonWriter.htm">JsonWriter</a></strong></td>
<td>
<div class="summary">Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.</div>
</td>
</tr>
<tr>
<td><img title="Public class" src="https://www.newtonsoft.com/json/help/icons/pubclass.gif" alt="Public class" /></td>
<td><strong><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonWriterException.htm">JsonWriterException</a></strong></td>
<td>
<div class="summary">The exception thrown when an error occurs while writing JSON text.</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="collapsibleAreaRegion"><span class="collapsibleRegionTitle"><img id="ID1RBToggle" class="collapseToggle" src="https://www.newtonsoft.com/json/help/icons/SectionExpanded.png" alt="" />Interfaces</span></div>
<div id="ID1RBSection" class="collapsibleSection">
<table id="interfaceList" class="members">
<tbody>
<tr><th class="iconColumn"> </th><th>Interface</th><th>Description</th></tr>
<tr>
<td><img title="Public interface" src="https://www.newtonsoft.com/json/help/icons/pubinterface.gif" alt="Public interface" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_IArrayPool_1.htm">IArrayPool<span id="LSTC5260D66_2"><T<span id="LSTC5260D66_3">></span></span></a></td>
<td>
<div class="summary">Provides an interface for using pooled arrays.</div>
</td>
</tr>
<tr>
<td><img title="Public interface" src="https://www.newtonsoft.com/json/help/icons/pubinterface.gif" alt="Public interface" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_IJsonLineInfo.htm">IJsonLineInfo</a></td>
<td>
<div class="summary">Provides an interface to enable a class to return line and position information.</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="collapsibleAreaRegion"><span class="collapsibleRegionTitle"><img id="ID2RBToggle" class="collapseToggle" src="https://www.newtonsoft.com/json/help/icons/SectionExpanded.png" alt="" />Enumerations</span></div>
<div id="ID2RBSection" class="collapsibleSection">
<table id="enumerationList" class="members">
<tbody>
<tr><th class="iconColumn"> </th><th>Enumeration</th><th>Description</th></tr>
<tr>
<td><img title="Public enumeration" src="https://www.newtonsoft.com/json/help/icons/pubenumeration.gif" alt="Public enumeration" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_ConstructorHandling.htm">ConstructorHandling</a></td>
<td>
<div class="summary">Specifies how constructors are used when initializing objects during deserialization by the <a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonSerializer.htm">JsonSerializer</a>.</div>
</td>
</tr>
<tr>
<td><img title="Public enumeration" src="https://www.newtonsoft.com/json/help/icons/pubenumeration.gif" alt="Public enumeration" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateFormatHandling.htm">DateFormatHandling</a></td>
<td>
<div class="summary">Specifies how dates are formatted when writing JSON text.</div>
</td>
</tr>
<tr>
<td><img title="Public enumeration" src="https://www.newtonsoft.com/json/help/icons/pubenumeration.gif" alt="Public enumeration" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateParseHandling.htm">DateParseHandling</a></td>
<td>
<div class="summary">Specifies how date formatted strings, e.g. <span class="code">"\/Date(1198908717056)\/" and <span class="code">"2012-03-21T05:40Z", are parsed when reading JSON text.</span></span></div>
</td>
</tr>
<tr>
<td><img title="Public enumeration" src="https://www.newtonsoft.com/json/help/icons/pubenumeration.gif" alt="Public enumeration" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateTimeZoneHandling.htm">DateTimeZoneHandling</a></td>
<td>
<div class="summary">Specifies how to treat the time value when converting between string and <a href="http://msdn2.microsoft.com/en-us/library/03ybds8y" target="_blank" rel="noopener noreferrer">DateTime</a>.</div>
</td>
</tr>
<tr>
<td><img title="Public enumeration" src="https://www.newtonsoft.com/json/help/icons/pubenumeration.gif" alt="Public enumeration" /><img title="Code example" src="https://www.newtonsoft.com/json/help/icons/CodeExample.png" alt="Code example" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htm">DefaultValueHandling</a></td>
<td>
<div class="summary">Specifies default value handling options for the <a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonSerializer.htm">JsonSerializer</a>.</div>
</td>
</tr>
<tr>
<td><img title="Public enumeration" src="https://www.newtonsoft.com/json/help/icons/pubenumeration.gif" alt="Public enumeration" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_FloatFormatHandling.htm">FloatFormatHandling</a></td>
<td>
<div class="summary">Specifies float format handling options when writing special floating point numbers, e.g. <a href="http://msdn2.microsoft.com/en-us/library/c8481tka" target="_blank" rel="noopener noreferrer">NaN</a>,<a href="http://msdn2.microsoft.com/en-us/library/7c4k7y8t" target="_blank" rel="noopener noreferrer">PositiveInfinity</a> and <a href="http://msdn2.microsoft.com/en-us/library/3x7fs67h" target="_blank" rel="noopener noreferrer">NegativeInfinity</a> with <a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonWriter.htm">JsonWriter</a>.</div>
</td>
</tr>
<tr>
<td><img title="Public enumeration" src="https://www.newtonsoft.com/json/help/icons/pubenumeration.gif" alt="Public enumeration" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_FloatParseHandling.htm">FloatParseHandling</a></td>
<td>
<div class="summary">Specifies how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.</div>
</td>
</tr>
<tr>
<td><img title="Public enumeration" src="https://www.newtonsoft.com/json/help/icons/pubenumeration.gif" alt="Public enumeration" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Formatting.htm">Formatting</a></td>
<td>
<div class="summary">Specifies formatting options for the <a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonTextWriter.htm">JsonTextWriter</a>.</div>
</td>
</tr>
<tr>
<td><img title="Protected enumeration" src="https://www.newtonsoft.com/json/help/icons/protenumeration.gif" alt="Protected enumeration" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonReader_State.htm">JsonReader<span id="LSTC5260D66_4">.State</span></a></td>
<td>
<div class="summary">Specifies the state of the reader.</div>
</td>
</tr>
<tr>
<td><img title="Public enumeration" src="https://www.newtonsoft.com/json/help/icons/pubenumeration.gif" alt="Public enumeration" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonToken.htm">JsonToken</a></td>
<td>
<div class="summary">Specifies the type of JSON token.</div>
</td>
</tr>
<tr>
<td><img title="Public enumeration" src="https://www.newtonsoft.com/json/help/icons/pubenumeration.gif" alt="Public enumeration" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_MemberSerialization.htm">MemberSerialization</a></td>
<td>
<div class="summary">Specifies the member serialization options for the <a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonSerializer.htm">JsonSerializer</a>.</div>
</td>
</tr>
<tr>
<td><img title="Public enumeration" src="https://www.newtonsoft.com/json/help/icons/pubenumeration.gif" alt="Public enumeration" /></td>
<td><a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_MetadataPropertyHandling.htm">MetadataPropertyHandling</a></td>
<td>
<div class="summary">Specifies metadata property handling options for the <a href="
文章评论