JSON序列化:

WebAPI的默认序列库使用的是Json.NET,可以在Globally中配置使用DataContractJsonSerializer 进行序列化 

        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.UseDataContractJsonSerializer = true;
        }

默认情况下,所有的公共的属性和字段都能被序列化(非公共的不能),除非声明了JsonIgnore特性

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    [JsonIgnore]
    public int ProductCode { get; set; } // 不能被序列化
}

或者使用一下方式,将需要序列化的元素显示标出来

[DataContract]
public class Product
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public decimal Price { get; set; }
    public int ProductCode { get; set; }  // 不能被序列化
}

JSON序列化时的一些设置【测试好像没效果,疑惑】

1  var json =  GlobalConfiguration.Configuration.Formatters.JsonFormatter;
2             //设置UTC时区
3             json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
4             //设置缩进
5             json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
6             //使用驼峰命名法
7             json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
8             //使用Microsoft JSON 时间格式("\/Date(ticks)\/")
9             json.SerializerSettings.DateFormatHandling= Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
View Code

相关文章:

  • 2022-02-19
  • 2021-07-08
  • 2022-03-04
  • 2021-10-01
  • 2022-12-23
  • 2022-01-12
  • 2022-02-05
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-07
  • 2022-12-23
相关资源
相似解决方案