Newtonsoft.Json是一个在.NET环境下开源的JSON格式序列化和反序列化的类库。它可以将.NET对象转换为JSON格式的字符串,也可以将JSON格式的字符串转换为.NET对象。这个类库在.NET开发中被广泛使用,因为它功能强大、易于使用,并且有良好的性能。
使用Newtonsoft.Json,你可以方便地进行以下操作:
要使用Newtonsoft.Json,你首先需要将其添加到你的项目中。你可以通过NuGet包管理器来安装它。一旦安装完成,你就可以在你的代码中使用它。
官网:https://www.newtonsoft.com/json/help/html/Introduction.htm
https://www.newtonsoft.com/json/help/html/SerializationSettings.htm
Converters: 一个包含自定义转换器的集合,这些转换器用于将对象序列化为 JSON 或从 JSON 反序列化为对象。 DateFormatHandling: 控制日期和时间格式的处理方式。例如,可以将日期格式化为特定的字符串格式,或者使用 ISO 8601 格式。 DateTimeZoneHandling: 控制日期时间值的时区处理方式。可以选择本地、UTC 或不处理。 IsoDateTimeFormat: 一个布尔值,用于指示是否将日期时间值格式化为 ISO 8601 格式。 SerializationMemberSelector: 一个委托,允许您自定义哪些属性将被序列化。 ReferenceLoopHandling: 控制循环引用的处理方式。可以选择忽略、警告或抛出异常。 MissingMemberHandling: 控制缺少成员的处理方式。可以选择忽略、抛出异常或引发警告。 DefaultSettings: 使用默认设置进行序列化。这些设置可以覆盖应用程序中的其他特定设置。 ContractResolver: 用于控制 JSON.NET 如何推断和创建 JSON 合同。这允许您自定义命名约定、忽略默认属性等。 NamingStrategy: 用于控制 JSON.NET 中的命名约定。例如,可以使用 CamelCase 或 PascalCase 命名约定。 StringEscapeHandling: 控制字符串转义字符的处理方式。可以选择逃逸或不逃逸转义字符。 ReferenceResolutionPolicy: 控制如何处理重复引用相同的对象。可以选择警告、忽略或抛出异常。 NullValueHandling: 控制如何处理空值。可以选择忽略、表示为 null 或使用默认值。
NQ to JSON 是用于处理 JSON 对象的 API。它在设计时考虑了 LINQ,可以快速查询和创建 JSON 对象。LINQ to JSON 位于 Newtonsoft.Json.Linq 命名空间下。
JObject o = JObject.Parse(@"{ 'CPU': 'Intel', 'Drives': [ 'DVD read/writer', '500 gigabyte hard drive' ]}");string cpu = (string)o["CPU"];// Intelstring firstDrive = (string)o["Drives"][0];// DVD read/writerIList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
JObject o = JObject.Parse(@"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
string cpu = (string)o["CPU"];
// Intel
string firstDrive = (string)o["Drives"][0];
// DVD read/writer
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
https://learn.microsoft.com/zh-cn/dotnet/standard/serialization/system-text-json/migrate-from-newtonsoft?pivots=dotnet-8-0#table-of-differences
NullValueHandling.Ignore
PreserveReferencesHandling
DefaultValueHandling
[JsonProperty]
NullValueHandling
Dictionary
[JsonConstructor]
ReferenceLoopHandling
Required
DefaultContractResolver
MissingMemberHandling
ObjectCreationHandling
object
null
DateTimeZoneHandling
DateFormatString
JsonConvert.PopulateObject
System.Runtime.Serialization
JsonObjectAttribute
TypeNameHandling.All
JsonPath
/// <summary> /// Json序列化反序列化类 /// </summary> public class JsonHelper { private static readonly JsonSerializerSettings _jsonSerializerSettings; static JsonHelper() { _jsonSerializerSettings = DefaultSerializerSettings; } private static JsonSerializerSettings DefaultSerializerSettings { get { var settings = new JsonSerializerSettings(); // 设置如何将日期写入JSON文本。默认值为“IsoDateFormat” //settings.DateFormatHandling = DateFormatHandling.IsoDateFormat; // 设置在序列化和反序列化期间如何处理DateTime时区。默认值为 “RoundtripKind” //settings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; // 设置在序列化和反序列化期间如何处理默认值。默认值为“Include” //settings.DefaultValueHandling = DefaultValueHandling.Include; // 设置写入JSON文本时DateTime和DateTimeOffset值的格式,以及读取JSON文本时预期的日期格式。默认值为“ yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK ”。 settings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 设置在序列化和反序列化期间如何处理空值。默认值为“Include” //settings.NullValueHandling = NullValueHandling.Include; // 设置序列化程序在将.net对象序列化为JSON时使用的契约解析器 settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 设置如何处理引用循环(例如,类引用自身)。默认值为“Error”。 settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 是否格式化文本 settings.Formatting = Formatting.Indented; //支持将Enum 由默认 Number类型 转换为String //settings.SerializerSettings.Converters.Add(new StringEnumConverter()); //将long类型转为string settings.SerializerSettings.Converters.Add(new NumberConverter(NumberConverterShip.Int64)); return settings; } } public static T Deserialize<T>(string json, JsonSerializerSettings serializerSettings = null) { if (string.IsNullOrEmpty(json)) return default; if (serializerSettings == null) serializerSettings = _jsonSerializerSettings; //值类型和String类型 if (typeof(T).IsValueType || typeof(T) == typeof(string)) { return (T)Convert.ChangeType(json, typeof(T)); } return JsonConvert.DeserializeObject<T>(json, serializerSettings); } public static string Serialize<T>(T obj, JsonSerializerSettings serializerSettings = null) { if (obj is null) return string.Empty; if (obj is string) return obj.ToString(); if (serializerSettings == null) serializerSettings = _jsonSerializerSettings; return JsonConvert.SerializeObject(obj, serializerSettings); } }
/// <summary>
/// Json序列化反序列化类
/// </summary>
public class JsonHelper
{
private static readonly JsonSerializerSettings _jsonSerializerSettings;
static JsonHelper()
_jsonSerializerSettings = DefaultSerializerSettings;
}
private static JsonSerializerSettings DefaultSerializerSettings
get
var settings = new JsonSerializerSettings();
// 设置如何将日期写入JSON文本。默认值为“IsoDateFormat”
//settings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
// 设置在序列化和反序列化期间如何处理DateTime时区。默认值为 “RoundtripKind”
//settings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
// 设置在序列化和反序列化期间如何处理默认值。默认值为“Include”
//settings.DefaultValueHandling = DefaultValueHandling.Include;
// 设置写入JSON文本时DateTime和DateTimeOffset值的格式,以及读取JSON文本时预期的日期格式。默认值为“ yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK ”。
settings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
// 设置在序列化和反序列化期间如何处理空值。默认值为“Include”
//settings.NullValueHandling = NullValueHandling.Include;
// 设置序列化程序在将.net对象序列化为JSON时使用的契约解析器
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// 设置如何处理引用循环(例如,类引用自身)。默认值为“Error”。
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
// 是否格式化文本
settings.Formatting = Formatting.Indented;
//支持将Enum 由默认 Number类型 转换为String
//settings.SerializerSettings.Converters.Add(new StringEnumConverter());
//将long类型转为string
settings.SerializerSettings.Converters.Add(new NumberConverter(NumberConverterShip.Int64));
return settings;
public static T Deserialize<T>(string json, JsonSerializerSettings serializerSettings = null)
if (string.IsNullOrEmpty(json)) return default;
if (serializerSettings == null) serializerSettings = _jsonSerializerSettings;
//值类型和String类型
if (typeof(T).IsValueType || typeof(T) == typeof(string))
return (T)Convert.ChangeType(json, typeof(T));
return JsonConvert.DeserializeObject<T>(json, serializerSettings);
public static string Serialize<T>(T obj, JsonSerializerSettings serializerSettings = null)
if (obj is null) return string.Empty;
if (obj is string) return obj.ToString();
return JsonConvert.SerializeObject(obj, serializerSettings);
public static class JsonSerializeExtensions { public static IMvcBuilder AddMCodeJsonOptions(this IMvcBuilder builder, Action<MvcNewtonsoftJsonOptions> configure = null) { /* */ builder.AddNewtonsoftJson(options => { // 设置如何将日期写入JSON文本。默认值为“IsoDateFormat” //options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat; // 设置在序列化和反序列化期间如何处理DateTime时区。默认值为 “RoundtripKind” //options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; // 设置在序列化和反序列化期间如何处理默认值。默认值为“Include” //options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include; // 设置写入JSON文本时DateTime和DateTimeOffset值的格式,以及读取JSON文本时预期的日期格式。默认值为“ yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK ”。 options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 设置在序列化和反序列化期间如何处理空值。默认值为“Include” //options.SerializerSettings.NullValueHandling = NullValueHandling.Include; // 设置序列化程序在将.net对象序列化为JSON时使用的契约解析器 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 设置如何处理引用循环(例如,类引用自身)。默认值为“Error”。 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 是否格式化文本 options.SerializerSettings.Formatting = Formatting.Indented; //将long类型转为string options.SerializerSettings.Converters.Add(new NumberConverter(NumberConverterShip.Int64)); configure.Invoke(options); }); return builder; } }
public static class JsonSerializeExtensions
public static IMvcBuilder AddMCodeJsonOptions(this IMvcBuilder builder, Action<MvcNewtonsoftJsonOptions> configure = null)
/*
*/
builder.AddNewtonsoftJson(options =>
//options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
//options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
//options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//options.SerializerSettings.NullValueHandling = NullValueHandling.Include;
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.Formatting = Formatting.Indented;
options.SerializerSettings.Converters.Add(new NumberConverter(NumberConverterShip.Int64));
configure.Invoke(options);
});
return builder;
微信:17873041739
原文链接:https://www.cnblogs.com/vic-tory/p/18055760
本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728