Using Newtonsoft.Json C# Json Serialization and Deserialization Tool: A Comprehensive Guide to Type Methods

2019年12月15日 106点热度 0人点赞 0条评论
内容目录

 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 |
|-------|-------------|
| Public class DefaultJsonNameTable |

The default JSON name table implementation.

|
| Public class JsonArrayAttribute |

Instructs the JsonSerializer how to serialize the collection.

|
| Public class JsonConstructorAttribute |

Instructs the JsonSerializer to use the specified constructor when deserializing that object.

|
| Public class JsonContainerAttribute |

Instructs the JsonSerializer how to serialize the object.

|
| Public classCode example JsonConvert |

Provides methods for converting between .NET types and JSON.

|
| Public class JsonConverter |

Converts an object to and from JSON.

|
| Public class JsonConverter<T> |

Converts an object to and from JSON.

|
| Public class JsonConverterAttribute |

Instructs the JsonSerializer to use the specified JsonConverter when serializing the member or class.

|
| Public class JsonConverterCollection |

Represents a collection of JsonConverter.

|
| Public class JsonDictionaryAttribute |

Instructs the JsonSerializer how to serialize the collection.

|
| Public classJsonException |

The exception type thrown when an error occurs during JSON serialization or deserialization.

|
| Public class JsonExtensionDataAttribute |

Instructs the JsonSerializer to deserialize properties with no matching class member into the specified collection and write values during serialization.

|
| Public class JsonIgnoreAttribute |

Instructs the JsonSerializer not to serialize the public field or public read/write property value.

|
| Public class JsonNameTable |

Base class for a table of atomized string objects.

|
| Public class JsonObjectAttribute |

Instructs the JsonSerializer how to serialize the object.

|
| Public class JsonPropertyAttribute |

Instructs the JsonSerializer to always serialize the member with the specified name.

|
| Public classJsonReader |

Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data.

|
| Public class JsonReaderException |

The exception thrown when an error occurs while reading JSON text.

|
| Public class JsonRequiredAttribute |

Instructs the JsonSerializer to always serialize the member, and to require that the member has a value.

|
| Public class JsonSerializationException |

The exception thrown when an error occurs during JSON serialization or deserialization.

|
| Public classJsonSerializer |

Serializes and deserializes objects into and from the JSON format. The JsonSerializer enables you to control how objects are encoded into JSON.

|
| Public class JsonSerializerSettings |

Specifies the settings on a JsonSerializer instance.

|

ewtonsoft_Json_JsonSerializer.htm">JsonSerializer</a>&nbsp;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&nbsp;<a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Schema_JsonSchema.htm">JsonSchema</a>&nbsp;validation.</p>
<div class="alert">
<table>
<tbody>
<tr><th><img src="https://www.newtonsoft.com/json/help/icons/AlertCaution.png" alt="Caution note" />&nbsp;Caution</th></tr>
<tr>
<td>JSON Schema validation has been moved to its own package. See&nbsp;<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">&nbsp;</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">&lt;T<span id="LSTC5260D66_3">&gt;</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">&nbsp;</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&nbsp;<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.&nbsp;<span class="code">"\/Date(1198908717056)\/"&nbsp;and&nbsp;<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&nbsp;<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&nbsp;<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.&nbsp;<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>&nbsp;and&nbsp;<a href="http://msdn2.microsoft.com/en-us/library/3x7fs67h" target="_blank" rel="noopener noreferrer">NegativeInfinity</a>&nbsp;with&nbsp;<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&nbsp;<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&nbsp;<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&nbsp;<a href="

=JsonSerializer.

Public enumeration MissingMemberHandling
Specifies missing member handling options for the JsonSerializer.
Public enumerationCode example NullValueHandling
Specifies null value handling options for the JsonSerializer.
Public enumeration ObjectCreationHandling
Specifies how object creation is handled by the JsonSerializer.
Public enumerationCode example PreserveReferencesHandling
Specifies reference handling options for the JsonSerializer. Note that references cannot be preserved when a value is set via a non-default constructor such as types that implement ISerializable.
Public enumeration ReferenceLoopHandling
Specifies reference loop handling options for the JsonSerializer.
Public enumeration Required
Indicating whether a property is required.
Public enumeration StringEscapeHandling
Specifies how strings are escaped when writing JSON text.
Public enumeration TypeNameAssemblyFormatHandling
Indicates the method that will be used during deserialization for locating and loading assemblies.
Public enumeration TypeNameHandling
Specifies type name handling options for the JsonSerializer.
Public enumeration WriteState
Specifies the state of the JsonWriter.
 


Additionally, here is the Baidu AI Optical Character Recognition (OCR) JSON and its model class

 Image

The author has been working on the Baidu AI platform SDK, encapsulating the OCR SDK. Since I am currently looking for an internship, some parts are not finished. Interested parties can add my WeChat for free access. WeChat is available in the navigation bar on the right.

Baidu AI recognizes text and returns JSON results. Choose a random name. The format is recommended to be JSON. If saved using Notepad, please note the encoding format is UTF-8, as C# strings default to UTF-8; otherwise, it may result in garbled text.

.</p>
<div class="cnblogs_code">
<pre><span style="color: #000000;">{
  "log_id": 3413661945235258919,
  "direction": 0,
  "words_result_num": 2,
  "words_result": [
    {
      "vertexes_location": [
        {
          "y": 81,
          "x": 51
        },
        {
          "y": 81,
          "x": 151
        },
        {
          "y": 103,
          "x": 151
        },
        {
          "y": 103,
          "x": 51
        }
      ],
      "probability": {
        "variance": 0.0,
        "average": 0.999861,
        "min": 0.999627
      },
      "chars": [
        {
          "char": "今",
          "location": {
            "width": 17,
            "top": 83,
            "left": 60,
            "height": 20
          }
        },
        {
          "char": "天",
          "location": {
            "width": 17,
            "top": 83,
            "left": 78,
            "height": 20
          }
        },
        {
          "char": "除",
          "location": {
            "width": 12,
            "top": 83,
            "left": 103,
            "height": 20
          }
        },
        {
          "char": "了",
          "location": {
            "width": 16,
            "top": 83,
            "left": 116,
            "height": 20
          }
        },
        {
          "char": "皮",
          "location": {
            "width": 13,
            "top": 83,
            "left": 140,
            "height": 20
          }
        }
      ],
      "min_finegrained_vertexes_location": [
        {
          "y": 81,
          "x": 51
        },
        {
          "y": 81,
          "x": 151
        },
        {
          "y": 103,
          "x": 151
        },
        {
          "y": 103,
          "x": 51
        }
      ],
      "finegrained_vertexes_location": [
        {
          "y": 81,
          "x": 51
        },
        {
          "y": 81,
          "x": 71
        },
        {
          "y": 81,
          "x": 90
        },
        {
          "y": 81,
          "x": 110
        },
        {
          "y": 81,
          "x": 129
        },
        {
          "y": 81,
          "x": 149
        },
        {
          "y": 81,
          "x": 151
        },
        {
          "y": 91,
          "x": 151
        },
        {
          "y": 100,
          "x": 151
        },
        {
          "y": 103,
          "x": 151
        },
        {
          "y": 103,
          "x": 132
        },
        {
          "y": 103,
          "x": 112
        },
        {
          "y": 103,
          "x": 93
        },
        {
          "y": 103,
          "x": 73
        },
        {
          "y": 103,
          "x": 54
        },
        {
          "y": 103,
          "x": 51
        },
        {
          "y": 93,
          "x": 51
        },
        {
          "y": 84,
          "x": 51
        }
      ],
      "location": {
        "width": 102,
        "top": 81,
        "left": 51,
        "height": 24
      },
      "words": "今天除了皮"
    },
    {
      "vertexes_location": [
        {
          "y": 109,
          "x": 52
        },
        {
          "y": 109,
          "x": 152
        },
        {
          "y": 130,
          "x": 152
        },
        {
          "y": 130,
          "x": 52
        }
      ],
      "probability": {
        "variance": 8E-05,
        "average": 0.9907,
        "min": 0.973259
      },
      "chars": [
        {
          "char": "又",
          "location": {
            "width": 16,
            "top": 111,
            "left": 61,
            "height": 20
          }
        },
        {
          "char": "啥",
          "location": {
            "width": 12,
            "top": 111,
            "left": 85,
            "height": 20
          }
        },
        {
          "char": "也",
          "location": {
            "width": 16,
            "top": 111,
            "left": 98,
            "height": 20
          }
        },
        {
          "char": "没",
          "location": {
            "width": 15,
            "top": 111,
            "left": 123,
            "height": 20
          }
        },
        {
          "char": "干",
          "location": {
            "width": 13,
            "top": 111,
            "left": 141,
            "height": 20
          }
        }
      ],
      "min_finegrained_vertexes_location": [
        {
          "y": 109,
          "x": 52
        },
        {
          "y": 109,
          "x": 152
        },
        {
          "y": 130,
          "x": 152
        },
        {
          "y": 130,
          "x": 52
        }
      ],
      "finegrained_vertexes_location": [
        {
          "y": 109,
          "x": 52
        },
        {
          "y": 109,
          "x": 71
        },
        {
          "y": 109,
          "x": 91
        },
        {
          "y": 109,
          "x": 110
        },
        {
          "y": 109,
          "x": 129
        },
        {
          "y": 109,
          "x": 149
        },
        {
          "y": 109,
          "x": 152
        },
        {
          "y": 119,
          "x": 152
        },
        {
          "y": 129,
          "x": 152
        },
        {
          "y": 130,
          "x": 152
        },
        {
          "y": 130,
          "x": 133
        },
        {
          "y": 130,
          "x": 113
        },
        {
          "y": 130,
          "x": 94
        },
        {
          "y": 130,
          "x": 74
        },
        {
          "y": 130,
          "x": 55
        },
        {
          "y": 130,
          "x": 52
        },
        {
          "y": 121,
          "x": 52
        },
        {
          "y": 111,
          "x": 52
        }
      ],
      "location": {
        "width": 102,
        "top": 109,
        "left": 52,
        "height": 22
      },
      "words": "又啥也没干"
    }
  ],
  "language": -1
}</span></pre>
</div>
<p>The corresponding model is a C# file named <strong>GeneralModel.cs</strong></p>
<div class="cnblogs_code">
<pre>    <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
    <span style="color: #808080;">///</span><span style="color: #008000;"> General text recognition (including location version) return results
    </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span><span style="color: #000000;"> GeneralModel
    {
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
        <span style="color: #808080;">///</span><span style="color: #008000;"> Required
        </span><span style="color: #808080;">///</span><span style="color: #008000;"> Unique log id for problem identification
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">long</span> log_id { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
        <span style="color: #808080;">///</span><span style="color: #008000;"> Image direction, exists when detect_direction=true

    </span><span style="color: #808080;">///</span><span style="color: #008000;"> Optional
    </span><span style="color: #808080;">///</span><span style="color: #008000;">- -1: Undefined,
    </span><span style="color: #808080;">///</span><span style="color: #008000;">- 0: Forward,
    </span><span style="color: #808080;">///</span><span style="color: #008000;">- 1: Counterclockwise 90 degrees,
    </span><span style="color: #808080;">///</span><span style="color: #008000;">- 2: Counterclockwise 180 degrees,
    </span><span style="color: #808080;">///</span><span style="color: #008000;">- 3: Counterclockwise 270 degrees
    </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> direction { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }

    </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
    <span style="color: #808080;">///</span><span style="color: #008000;"> Required
    </span><span style="color: #808080;">///</span><span style="color: #008000;"> The number of recognized results, representing the number of elements in words_result
    </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> words_result_num { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }

    </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
    <span style="color: #808080;">///</span><span style="color: #008000;"> Language detection. The default value is -1
    </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">string</span> language { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
    </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
    <span style="color: #808080;">///</span><span style="color: #008000;"> Array of text recognition results with location information
    </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
    <span style="color: #0000ff;">public</span> List&lt;Words_result&gt; words_result { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }

    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span><span style="color: #000000;"> Words_result
    {
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
        <span style="color: #808080;">///</span><span style="color: #008000;"> The positions of the four vertices of the text field in the image (rectangular area)
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
        <span style="color: #0000ff;">public</span> List&lt;XY&gt; vertexes_Location { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
        <span style="color: #808080;">///</span><span style="color: #008000;"> Optional
        </span><span style="color: #808080;">///</span><span style="color: #008000;"> Row confidence information; output if input parameter probability = true
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
        <span style="color: #0000ff;">public</span> Probability probability { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
        <span style="color: #808080;">///</span><span style="color: #008000;"> Each character
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
        <span style="color: #0000ff;">public</span> List&lt;Chars&gt; chars { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
        <span style="color: #808080;">///</span><span style="color: #008000;"> Minimum fine-grained vertex coordinates
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
        <span style="color: #0000ff;">public</span> List&lt;XY&gt; min_finegrained_vertexes_location { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
        <span style="color: #808080;">///</span><span style="color: #008000;"> Fine-grained vertex coordinates, polygon
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
        <span style="color: #0000ff;">public</span> List&lt;XY&gt; finegrained_vertexes_location { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
        <span style="color: #808080;">///</span><span style="color: #008000;"> The relative position of the text in the image
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
        <span style="color: #0000ff;">public</span> Location location { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
        <span style="color: #808080;">///</span><span style="color: #008000;"> Recognized text
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">string</span> words { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
        <span style="color: #808080;">///</span><span style="color: #008000;"> Coordinates
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span><span style="color: #000000;"> XY
        {
            </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> x { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
            </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> y { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
        }
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
        <span style="color: #808080;">///</span><span style="color: #008000;"> Row confidence
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span><span style="color: #000000;"> Probability
        {
            </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
            <span style="color: #808080;">///</span><span style="color: #008000;"> Variance of average row confidence
            </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
            <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">double</span> variance { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
            </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
            <span style="color: #808080;">///</span><span style="color: #008000;"> Average row confidence
            </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
            <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">double</span> average { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }

            </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
            <span style="color: #808080;">///</span><span style="color: #008000;"> Minimum row confidence
            </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
            <span style="color: #0000ff;">public</span> <span style="color: #0000ff;'>double</span> min { <span style="color: #0000ff;'>get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
        }
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
        <span style="color: #808080;">///</span><span style="color: #008000;"> Individual character
        </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>

<span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span><span style="color: #000000;"> Chars
            {
                </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
                <span style="color: #808080;">///</span><span style="color: #008000;"> Recognized single character
                </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
                <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">char</span> chaR { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
                </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
                <span style="color: #808080;">///</span><span style="color: #008000;"> The bounding box of this character (rectangle)
                </span><span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
                <span style="color: #0000ff;">public</span> Location location { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
            }
        }
        </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span><span style="color: #000000;"> Location
        {
            </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> left { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
            </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> top { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
            </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> width { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
            </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> height { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span><span style="color: #000000;">; }
        }
    }
}</span></pre>
</div>
<p>Verification can be done through the console</p>
<div class="cnblogs_code">
<pre> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> Main(<span style="color: #0000ff;">string</span><span style="color: #000000;">[] args)
        {
            StreamReader streamReader </span>= <span style="color: #0000ff;">new</span> StreamReader(System.IO.File.OpenRead(<span style="color: #800000;">@"</span><span style="color: #800000;">json file location</span><span style="color: #800000;">"</span><span style="color: #000000;">));
            </span><span style="color: #0000ff;">string</span> str = <span style="color: #800000;">""</span><span style="color: #000000;">;
            </span><span style="color: #0000ff;">string</span><span style="color: #000000;"> jsonstr;
            </span><span style="color: #0000ff;">while</span> ((jsonstr = streamReader.ReadLine()) != <span style="color: #0000ff;">null</span><span style="color: #000000;">)
            {
                str </span>+=<span style="color: #000000;"> jsonstr;
            }

            GeneralModel generalModel </span>= JsonConvert.DeserializeObject&lt;GeneralModel&gt;<span style="color: #000000;">(str);

            Console.WriteLine(</span><span style="color: #800000;">"</span><span style="color: #800000;">Image ID:</span><span style="color: #800000;">"</span> +<span style="color: #000000;"> generalModel.log_id);
            Console.WriteLine(</span><span style="color: #800000;">"</span><span style="color: #800000;">Image Direction:</span><span style="color: #800000;">"</span> +<span style="color: #000000;"> generalModel.direction);
            Console.WriteLine(</span><span style="color: #800000;">"</span><span style="color: #800000;">Detected Language:</span><span style="color: #800000;">"</span> +<span style="color: #000000;"> generalModel.language);
            Console.WriteLine(</span><span style="color: #800000;">"</span><span style="color: #800000;">Number of Results:</span><span style="color: #800000;">"</span> +<span style="color: #000000;"> generalModel.words_result_num);

            </span><span style="color: #0000ff;">foreach</span> (<span style="color: #0000ff;">var</span> item <span style="color: #0000ff;">in</span><span style="color: #000000;"> generalModel.words_result)
            {

                Console.WriteLine(</span><span style="color: #800000;">"</span><span style="color: #800000;">Recognition Result:</span><span style="color: #800000;">"</span> +<span style="color: #000000;"> Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(item.words)));
                </span><span style="color: #0000ff;">foreach</span> (<span style="color: #0000ff;">var</span> itemi <span style="color: #0000ff;">in</span><span style="color: #000000;"> item.vertexes_Location)
                {
                    Console.WriteLine(</span><span style="color: #800000;">"</span><span style="color: #800000;">{x:</span><span style="color: #800000;">"</span> + itemi.x + <span style="color: #800000;">"</span><span style="color: #800000;">;y:</span><span style="color: #800000;">"</span> + itemi.y + <span style="color: #800000;">"</span><span style="color: #800000;">}</span><span style="color: #800000;">"</span><span style="color: #000000;">);
                }
                Console.WriteLine(</span><span style="color: #800000;">"</span><span style="color: #800000;">Probability: Confidence:</span><span style="color: #800000;">"</span> + <span style="color: #800000;">"</span><span style="color: #800000;">Line Confidence Average:</span><span style="color: #800000;">"</span> + item.probability.average + <span style="color: #800000;">"</span><span style="color: #800000;">; Line Confidence Average Variance:</span><span style="color: #800000;">"</span> + item.probability.variance + <span style="color: #800000;">"</span><span style="color: #800000;">; Line Confidence Average Minimum:</span><span style="color: #800000;">"</span> +<span style="color: #000000;"> item.probability.min);
                </span><span style="color: #0000ff;">foreach</span> (<span style="color: #0000ff;">var</span> itemi <span style="color: #0000ff;">in</span><span style="color: #000000;"> item.chars)
                {
                    Console.WriteLine(itemi.chaR);
                    Console.WriteLine(</span><span style="color: #800000;">"</span><span style="color: #800000;">Location:  left:</span><span style="color: #800000;">"</span> + itemi.location.left + <span style="color: #800000;">"</span><span style="color: #800000;">;  height: </span><span style="color: #800000;">"</span> + itemi.location.height + <span style="color: #800000;">"</span><span style="color: #800000;">top: </span><span style="color: #800000;">"</span> + itemi.location.top + <span style="color: #800000;">"</span><span style="color: #800000;">; width: </span><span style="color: #800000;">"</span> +<span style="color: #000000;"> itemi.location.width);
                }
            }

            Console.ReadKey();</span></pre>
</div>
<p>&nbsp;

痴者工良

高级程序员劝退师

文章评论