Newtonsoft.Json
Newtonsoft.Json 是.Net平台操作Json的工具,他的介绍就不多说了,笔者最近在弄接口,需要操作Json。
以某个云计算平台的Token为例,边操作边讲解。
Json 转为 Model
将 Model 转为 Json
将 LINQ 转为 JSON
Linq 操作
命名空间、类型、方法大全
另外附上 百度AI 文字识别 Json 及其模型类
Newtonsoft.Json 将字符串转为对象,是根据类型对象名称进行的,大小写不分,但是名称要一致要,哪怕你的json只有一个
{ "a":1 }
你的对象
public class Test { int aa{get;set;} }
也是不能对应的。
有复杂层次的 json,可以使用 “类中类” 来映射,要注意 List<T>/Array/ArrayList的类型的使用。
Json 转为 Model
新建一个 Json 文件,名字随意,例如 json1.json
把以下内容粘贴进去
{ refresh_token": 25.ea2f85ebd48df85fe5400000.18640.282335-15533349",expires_in2592010session_key9mzdWr3n8ncmeDgX8zjhkhlW8khb5cdZtPevPbPwQGBg==access_token24.ac0ca9fakhlkyhl552017858.282335-15533349scopeaudio_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_openapisession_secret2ca66d464545c77a4767f709873be4 }
定义一个模型,文件名为 AccesstokenModel.cs
AccesstokenModel { string refresh_token { get; ; } string expires_in { set; }//: Access Token的有效期(秒为单位,一般为1个月) string scope { string session_key { string access_token { : 要获取的Access Token string session_secret { ; } }
打开 Program.cs 文件
static void Main(string[] args) { FileStream fs = new FileStream(@"请修改成你的文件路径\json1.jsonnew StreamReader(fs); string str = ""; line; while ((line = fileStream.ReadLine()) != null) { str += line; }
//上面的代码没有意义,只是将Json文件的内容加载到字符串中
JObject jObject = JObject(); //新建 操作对象 AccesstokenModel a = JsonConvert.DeserializeObject<AccesstokenModel>(str); Console.WriteLine(a.access_token); //随意输出一个属性 Console.ReadKey(); }
重点方法
JsonConvert.DeserializeObject<要转化的模型类>("字符串对象");
集合
把Json文件改成以下的样子
[{ },{ } ]
@"请修改成你的文件路径\json1.json 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 文件,
[] args) { AccesstokenModel accesstokenModel = 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 = JObject(); string str = JsonConvert.SerializeObject(accesstokenModel); //转为字符串 Console.WriteLine(str); Console.ReadKey(); }
重点方法
JsonConvert.SerializeObject(a模型对象);
运行后可以看到控制台输出的是Json字符串了,你可以继续把他放到Json文件中,这里不再赘述。
将 LINQ 转为 JSON
下面这个是从官网直接copy的例子,Jarray 是其框架提供的一种类型。
在控制台运行后会发现输出的字符是已经格式化的。
[] args) { JArray array = JArray(); array.Add(Manual text); array.Add(new DateTime(2000,5,1)">23)); JObject o = 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一样方便。
命名空间、类型、方法大全
本来想翻译一下的,英语太差,算了。在常用的类型前面加粗吧
Class | Description | |||
---|---|---|---|---|
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,forward-only access to JSON text data.
|
|||
JsonTextWriter |
Represents a writer that provides a fast,forward-only way of generating JSON data.
|
|||
JsonValidatingReader |
Obsolete.
Represents a reader that provides JsonSchema validation.
|
|||
JsonWriter |
Represents a writer that provides a fast,forward-only way of generating JSON data.
|
|||
JsonWriterException |
The exception thrown when an error occurs while writing JSON text.
|