cs
/// <summary>
/// 转化为json的时候long类型转为string
/// </summary>
public class LongJsonConverter: JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return reader.Value.ObjToLong();
}
catch (Exception ex)
{
throw ex;
}
}
public override bool CanConvert(Type objectType)
{
return true;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
string sValue = value.ToString();
writer.WriteValue(sValue);
}
}
全局使用
cs
services.AddControllers(options =>
{
//添加过滤器
//options.Filters.Add(new AdminIpFilter(Configuration));
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.Converters.Add(new Common.NewtonsoftJsonConvert.LongNullConverter());
//修改属性名称的序列化方式,首字母小写
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
//修改时间的序列化方式
options.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
//看这里
options.SerializerSettings.Converters.Add(new LongJsonConverter());
});
针对某个属性使用
cs
[JsonConverter(typeof(LongJsonConverter))]
public long? Id { get; set; }