本文主要是介绍C# newtonsoft序列化将long类型转化为字符串,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/// <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);}
}
全局使用
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());});
针对某个属性使用
[JsonConverter(typeof(LongJsonConverter))]
public long? Id { get; set; }
这篇关于C# newtonsoft序列化将long类型转化为字符串的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!