1. 程式人生 > >Newtonsoft.Json Json工具的使用、類型方法大全

Newtonsoft.Json Json工具的使用、類型方法大全

source typename fas lex object base 使用 art 命名空間

Newtonsoft.Json

Newtonsoft.Json 是.Net平臺操作Json的工具,他的介紹就不多說了,筆者最近在弄接口,需要操作Json。

以某個雲計算平臺的Token為例,邊操作邊講解。

Json 轉為 Model

將 Model 轉為 Json

將 LINQ 轉為 JSON

Linq 操作

命名空間、類型、方法大全


Json 轉為 Model

新建一個 Json 文件,名字隨意,例如 json1.json

把以下內容粘貼進去

{
  "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" }

定義一個模型,文件名為 AccessTokenModel.cs

    public class AccessTokenModel
    {
        public string refresh_token { get; set; }
        public string expires_in { get; set; }//: Access Token的有效期(秒為單位,一般為1個月)
        public string scope { get; set; }
        
public string session_key { get; set; } public string access_token { get; set; }//: 要獲取的Access Token public string session_secret { get; set; } }

打開 Program.cs 文件

            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;
                }
          //上面的代碼沒有意義,只是將Json文件的內容加載到字符串中
           JObject jObject
= new JObject();        //新建 操作對象 AccessTokenModel a = JsonConvert.DeserializeObject<AccessTokenModel>(str); Console.WriteLine(a.access_token);    //隨意輸出一個屬性 Console.ReadKey(); }

重點方法

JsonConvert.DeserializeObject<要轉化的模型類>("字符串對象");

之後可以很方便的把Json文件的內容存放到數據庫中。

集合

把Json文件改成以下的樣子

[{
  "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;
                }
                //上面的代碼沒有意義,只是將Json文件的內容加載到字符串中

                JObject jObject = new JObject();        //新建 操作對象
                List<AccessTokenModel> a = JsonConvert.DeserializeObject<List<AccessTokenModel>>(str);
                foreach (var i in a)
                {
                    Console.WriteLine(i.access_token);
                }

                Console.ReadKey();
            }


將Model轉為Json

能夠將模型對象轉為 Json。

繼續使用上面的 AccessTokenModel.cs 文件,

            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);    //轉為字符串

                Console.WriteLine(str);
                Console.ReadKey();
            }

重點方法

JsonConvert.SerializeObject(a模型對象);

運行後可以看到控制臺輸出的是Json字符串了,你可以繼續把他放到Json文件中,這裏不再贅述。


將 LINQ 轉為 JSON

下面這個是從官網直接copy的例子,Jarray 是其框架提供的一種類型。

在控制臺運行後會發現輸出的字符是已經格式化的。

            public static void Main(string[] args)
            {
                JArray array = new JArray();
                array.Add("Manual text");
                array.Add(new DateTime(2000, 5, 23));

                JObject o = new JObject();
                o["MyArray"] = array;

                string json = o.ToString();
                // {
                //   "MyArray": [
                //     "Manual text",
                //     "2000-05-23T00:00:00"
                //   ]
                // }

                Console.WriteLine(json);
                Console.ReadKey();


Linq 操作

框架提供了對 Jobject 對象的Linq操作支持

using Newtonsoft.Json.Linq;

之後你可以像操作數組、集合或者Context一樣方便。


命名空間、類型、方法大全

技術分享圖片

本來想翻譯一下的,英語太差,算了。在常用的類型前面加粗吧

Classes
ClassDescription
技術分享圖片 DefaultJsonNameTable The default JSON name table implementation.
技術分享圖片 JsonArrayAttribute Instructs the JsonSerializer how to serialize the collection.
技術分享圖片 JsonConstructorAttribute Instructs the JsonSerializer to use the specified constructor when deserializing that object.
技術分享圖片 JsonContainerAttribute Instructs the JsonSerializer how to serialize the object.
技術分享圖片技術分享圖片 JsonConvert 提供用於在.NET 和 Json之間互相轉等操作的方法
技術分享圖片 JsonConverter Converts an object to and from JSON.
技術分享圖片 JsonConverter<T> Converts an object to and from JSON.
技術分享圖片 JsonConverterAttribute Instructs the JsonSerializer to use the specified JsonConverter when serializing the member or class.
技術分享圖片 JsonConverterCollection Represents a collection of JsonConverter.
技術分享圖片 JsonDictionaryAttribute Instructs the JsonSerializer how to serialize the collection.
技術分享圖片 JsonException JSON序列化或反序列化過程中發生錯誤時引發的異常類型
技術分享圖片 JsonExtensionDataAttribute Instructs the JsonSerializer to deserialize properties with no matching class member into the specified collection and write values during serialization.
技術分享圖片 JsonIgnoreAttribute Instructs the JsonSerializer not to serialize the public field or public read/write property value.
技術分享圖片 JsonNameTable Base class for a table of atomized string objects.
技術分享圖片 JsonObjectAttribute Instructs the JsonSerializer how to serialize the object.
技術分享圖片 JsonPropertyAttribute Instructs the JsonSerializer to always serialize the member with the specified name.
技術分享圖片 JsonReader Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data.
技術分享圖片 JsonReaderException The exception thrown when an error occurs while reading JSON text.
技術分享圖片 JsonRequiredAttribute Instructs the JsonSerializer to always serialize the member, and to require that the member has a value.
技術分享圖片 JsonSerializationException The exception thrown when an error occurs during JSON serialization or deserialization.
技術分享圖片 JsonSerializer Serializes and deserializes objects into and from the JSON format. The JsonSerializer enables you to control how objects are encoded into JSON.
技術分享圖片 JsonSerializerSettings Specifies the settings on a JsonSerializer object.
技術分享圖片 JsonTextReader Represents a reader that provides fast, non-cached, forward-only access to JSON text data.
技術分享圖片 JsonTextWriter Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
技術分享圖片 JsonValidatingReader Obsolete.

Represents a reader that provides JsonSchema validation.

技術分享圖片 Caution
JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschemafor more details.
技術分享圖片 JsonWriter Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
技術分享圖片 JsonWriterException The exception thrown when an error occurs while writing JSON text.
技術分享圖片Interfaces
InterfaceDescription
技術分享圖片 IArrayPool<T> Provides an interface for using pooled arrays.
技術分享圖片 IJsonLineInfo Provides an interface to enable a class to return line and position information.
技術分享圖片Enumerations
EnumerationDescription
技術分享圖片 ConstructorHandling Specifies how constructors are used when initializing objects during deserialization by the JsonSerializer.
技術分享圖片 DateFormatHandling Specifies how dates are formatted when writing JSON text.
技術分享圖片 DateParseHandling Specifies how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON text.
技術分享圖片 DateTimeZoneHandling Specifies how to treat the time value when converting between string and DateTime.
技術分享圖片技術分享圖片 DefaultValueHandling Specifies default value handling options for the JsonSerializer.
技術分享圖片 FloatFormatHandling Specifies float format handling options when writing special floating point numbers, e.g. NaN,PositiveInfinity and NegativeInfinity with JsonWriter.
技術分享圖片 FloatParseHandling Specifies how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
技術分享圖片 Formatting Specifies formatting options for the JsonTextWriter.
技術分享圖片 JsonReader.State Specifies the state of the reader.
技術分享圖片 JsonToken Specifies the type of JSON token.
技術分享圖片 MemberSerialization Specifies the member serialization options for the JsonSerializer.
技術分享圖片 MetadataPropertyHandling Specifies metadata property handling options for the JsonSerializer.
技術分享圖片 MissingMemberHandling Specifies missing member handling options for the JsonSerializer.
技術分享圖片技術分享圖片 NullValueHandling Specifies null value handling options for the JsonSerializer.
技術分享圖片 ObjectCreationHandling Specifies how object creation is handled by the JsonSerializer.
技術分享圖片技術分享圖片 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.
技術分享圖片 ReferenceLoopHandling Specifies reference loop handling options for the JsonSerializer.
技術分享圖片 Required Indicating whether a property is required.
技術分享圖片 StringEscapeHandling Specifies how strings are escaped when writing JSON text.
技術分享圖片 TypeNameAssemblyFormatHandling Indicates the method that will be used during deserialization for locating and loading assemblies.
技術分享圖片 TypeNameHandling Specifies type name handling options for the JsonSerializer.
技術分享圖片 WriteState Specifies the state of the JsonWriter.

Newtonsoft.Json Json工具的使用、類型方法大全