Newtonsoft.Json
是一个非常流行的 C# JSON 序列化和反序列化库,它可以方便地将 C# 对象转换为 JSON 格式,或者将 JSON 数据解析为 C# 对象。Newtonsoft.Json
被广泛用于处理 JSON 数据,因其简单、高效且功能强大。
以下是 Newtonsoft.Json
在 C# 中的详细使用教程。
在使用 Newtonsoft.Json
之前,你需要安装它。最简单的方式是通过 NuGet:
Newtonsoft.Json
,然后点击“安装”。也可以使用以下命令通过 NuGet 控制台安装:
Install-Package Newtonsoft.Json
要将 C# 对象转换为 JSON 字符串,可以使用 JsonConvert.SerializeObject()
方法。
usingNewtonsoft.Json;publicclassPerson{ publicstringName { get;set;}publicintAge { get;set;}}varperson =newPerson{ Name ="John",Age =30};stringjson =JsonConvert.SerializeObject(person);Console.WriteLine(json);
输出:
{ "Name":"John","Age":30}
要将 JSON 字符串转换为 C# 对象,可以使用 JsonConvert.DeserializeObject
方法。
stringjson ="{ \"Name\":\"John\",\"Age\":30}";Personperson =JsonConvert.DeserializeObject<Person>(json);Console.WriteLine(person.Name);// 输出:JohnConsole.WriteLine(person.Age);// 输出:30
为了提高可读性,可以使用 Formatting.Indented
选项将 JSON 格式化为缩进的样式:
stringformattedJson =JsonConvert.SerializeObject(person,Formatting.Indented);Console.WriteLine(formattedJson);
输出:
{ "Name":"John","Age":30}
Newtonsoft.Json
可以处理复杂的对象,例如包含嵌套对象或集合的对象。
publicclassAddress{ publicstringStreet { get;set;}publicstringCity { get;set;}}publicclassPerson{ publicstringName { get;set;}publicintAge { get;set;}publicAddressAddress { get;set;}}varperson =newPerson{ Name ="John",Age =30,Address =newAddress{ Street ="123 Main St",City ="New York"}};stringjson =JsonConvert.SerializeObject(person,Formatting.Indented);Console.WriteLine(json);
输出:
{ "Name":"John","Age":30,"Address":{ "Street":"123 Main St","City":"New York"}}
可以将 JSON 解析为动态对象,允许你在运行时灵活地访问 JSON 数据。
stringjson ="{ \"Name\":\"John\",\"Age\":30}";dynamicobj =JsonConvert.DeserializeObject<dynamic>(json);Console.WriteLine(obj.Name);// 输出:JohnConsole.WriteLine(obj.Age);// 输出:30
如果你不希望某些属性被序列化,可以使用 JsonIgnore
特性。
publicclassPerson{ publicstringName { get;set;}[JsonIgnore]publicintAge { get;set;}}varperson =newPerson{ Name ="John",Age =30};stringjson =JsonConvert.SerializeObject(person);Console.WriteLine(json);// 输出:{ "Name":"John"}
可以使用 JsonProperty
特性为属性指定自定义的 JSON 字段名称。
publicclassPerson{ [JsonProperty("full_name")]publicstringName { get;set;}[JsonProperty("years")]publicintAge { get;set;}}varperson =newPerson{ Name ="John",Age =30};stringjson =JsonConvert.SerializeObject(person);Console.WriteLine(json);// 输出:{ "full_name":"John","years":30}
可以自定义枚举的序列化方式,使其输出字符串,而不是数字。
publicenumGender{ Male,Female}publicclassPerson{ publicstringName { get;set;}publicGenderGender { get;set;}}varperson =newPerson{ Name ="John",Gender =Gender.Male};stringjson =JsonConvert.SerializeObject(person);Console.WriteLine(json);// 输出:{ "Name":"John","Gender":0}stringjsonWithStringEnum =JsonConvert.SerializeObject(person,newStringEnumConverter());Console.WriteLine(jsonWithStringEnum);// 输出:{ "Name":"John","Gender":"Male"}
通过 JsonSerializerSettings
,你可以更细粒度地控制 JSON 序列化和反序列化行为。
JsonSerializerSettingssettings =newJsonSerializerSettings{ NullValueHandling =NullValueHandling.Ignore,DefaultValueHandling =DefaultValueHandling.Ignore};stringjson =JsonConvert.SerializeObject(person,settings);Console.WriteLine(json);
你可以通过实现 JsonConverter
自定义对象的序列化和反序列化行为。
publicclassCustomPersonConverter:JsonConverter<Person>{ publicoverridevoidWriteJson(JsonWriterwriter,Personvalue,JsonSerializerserializer){ writer.WriteStartObject();writer.WritePropertyName("full_name");writer.WriteValue(value.Name);writer.WriteEndObject();}publicoverridePersonReadJson(JsonReaderreader,TypeobjectType,PersonexistingValue,boolhasExistingValue,JsonSerializerserializer){ JObjectjo =JObject.Load(reader);returnnewPerson{ Name =(string)jo["full_name"]};}}varperson =newPerson{ Name ="John",Age =30};stringcustomJson =JsonConvert.SerializeObject(person,newCustomPersonConverter());Console.WriteLine(customJson);// 输出:{ "full_name":"John"}PersoncustomPerson =JsonConvert.DeserializeObject<Person>(customJson,newCustomPersonConverter());Console.WriteLine(customPerson.Name);// 输出:John
你可以将 JSON 数组序列化和反序列化为 C# 集合类型,如 List
或数组。
stringjsonArray ="[{ \"Name\":\"John\",\"Age\":30},{ \"Name\":\"Jane\",\"Age\":25}]";List<Person>people =JsonConvert.DeserializeObject<List<Person>>(jsonArray);foreach(varperson inpeople){ Console.WriteLine($"{ person.Name}, { person.Age}");}
Newtonsoft.Json
是 C# 中最常用的 JSON 序列化和反序列化库之一,具有强大的功能和易于使用的 API。它能够处理简单和复杂的对象,支持定制化序列化、反序列化,适用于动态对象以及复杂的数据结构。