WebApi输出json 不要把首字母转为小写

            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 = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

                //忽略null值
                opt.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                opt.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();

                //让double不要使用科学计数法
                opt.SerializerSettings.Converters.Add(new Way.Lib.DoubleToDecimalConverter());
            });

 

posted @ 2020-08-19 11:05  IWing  阅读(693)  评论(0编辑  收藏  举报