services.AddControllers().AddJsonOptions(c => { c.JsonSerializerOptions.PropertyNamingPolicy = new NormalPolicy(); });
public class NormalPolicy : JsonNamingPolicy { public override string ConvertName(string name) => name; }
这是webapi内置的json转换器,但有个问题,如果一个json对象,里面有个属性是int?类型,用字符串转换过去,会失败。
{ "age":"18" } 转对象 class Person { public int? age {get;set;} } 会提示类型转换错误
方法二(推举)
nuget引用 Microsoft.AspNetCore.Mvc.NewtonsoftJson
services.AddControllers().AddNewtonsoftJson(opt => {
//忽略循环引用 opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//忽略null值
opt.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
opt.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); });