这里拿.Net Core 6 来做演示
在Program.cs中加入如下代码:
builder.Services.AddControllersWithViews().AddNewtonsoftJson(options =>
{
//循环引用
options.SerializerSettings.ReferenceLoopHandling=Newtonsoft.Json.ReferenceLoopHandling.Ignore;
//空值处理
options.SerializerSettings.NullValueHandling=Newtonsoft.Json.NullValueHandling.Ignore;
//大小写、处理雪花Id精度丢失
options.SerializerSettings.ContractResolver = new CustomContractResolver();
//修改时间的序列化方式
options.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy/MM/dd HH:mm:ss" });
});
代码中的CustomContractResolver是单独写了一个帮助类,作用是对长整形数据做处理具体代码如下:
public class CustomContractResolver : DefaultContractResolver
{
/// <summary>
/// 对长整型做处理
/// </summary>
/// <param name="objectType"></param>
/// <returns></returns>
protected override JsonConverter ResolveContractConverter(Type objectType)
{
if (objectType == typeof(long))
{
return new JsonConverterLong();
}
return base.ResolveContractConverter(objectType);
}
}
自己创建一个名为CustomContractResolver类然后输入上面的代码。
最后在CustomContractResolver.cs中还有一个JsonConverterLong,这也是一个需要单独去创建的一个类需要去做处理代码如下:
public class JsonConverterLong : JsonConverter
{
/// <summary>
/// 是否可以转换
/// </summary>
/// <param name="objectType"></param>
/// <returns></returns>
public override bool CanConvert(Type objectType)
{
return true;
}
/// <summary>
/// 读json
/// </summary>
/// <param name="reader"></param>
/// <param name="objectType"></param>
/// <param name="existingValue"></param>
/// <param name="serializer"></param>
/// <returns></returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if ((reader.ValueType == null || reader.ValueType == typeof(long?)) && reader.Value == null)
{
return null;
}
else
{
long.TryParse(reader.Value != null ? reader.Value.ToString() : "", out long value);
return value;
}
}
/// <summary>
/// 写json
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="serializer"></param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
writer.WriteValue(value);
else
writer.WriteValue(value + "");
}
}
最后就大功告成了赶紧去试试吧!
标签:return,CustomContractResolver,雪花,value,public,options,丢失,reader,Id From: https://www.cnblogs.com/zkmblog/p/17565669.html