https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/json-and-xml-serialization

JSON Media-Type Formatter

JSON formatting is provided by the JsonMediaTypeFormatter class. By default, JsonMediaTypeFormatter uses the Json.NET library to perform serialization. Json.NET is a third-party open source project.

If you prefer, you can configure the JsonMediaTypeFormatter class to use the DataContractJsonSerializer instead of Json.NET. To do so, set the UseDataContractJsonSerializer property to true:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.UseDataContractJsonSerializer = true;

JSON Serialization

This section describes some specific behaviors of the JSON formatter, using the default Json.NET serializer.

This is not meant to be comprehensive documentation of the Json.NET library; for more information, see the Json.NET Documentation.

What Gets Serialized?

By default, all public properties and fields are included in the serialized JSON. To omit a property or field, decorate it with the JsonIgnore attribute.

public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
[JsonIgnore]
public int ProductCode { get; set; } // omitted
}

If you prefer an "opt-in" approach, decorate the class with the DataContract attribute.

If this attribute is present, members are ignored unless they have the DataMember.

You can also use DataMember to serialize private members.

[DataContract]
public class Product
{
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal Price { get; set; }
public int ProductCode { get; set; } // omitted by default
}

Read-Only Properties

Read-only properties are serialized by default.

Dates

By default, Json.NET writes dates in ISO 8601 format. Dates in UTC (Coordinated Universal Time) are written with a "Z" suffix. Dates in local time include a time-zone offset. For example:

2012-07-27T18:51:45.53403Z         // UTC
2012-07-27T11:51:45.53403-07:00 // Local

By default, Json.NET preserves the time zone. You can override this by setting the DateTimeZoneHandling property:

// Convert all dates to UTC
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;

If you prefer to use Microsoft JSON date format ("\/Date(ticks)\/") instead of ISO 8601, set the DateFormatHandling property on the serializer settings:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;

Indenting

To write indented JSON, set the Formatting setting to Formatting.Indented:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;

Camel Casing

To write JSON property names with camel casing, without changing your data model, set the CamelCasePropertyNamesContractResolver on the serializer:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

Anonymous and Weakly-Typed Objects

An action method can return an anonymous object and serialize it to JSON. For example:

public object Get()
{
return new {
Name = "Alice",
Age = ,
Pets = new List<string> { "Fido", "Polly", "Spot" }
};
}

The response message body will contain the following JSON:

{"Name":"Alice","Age":23,"Pets":["Fido","Polly","Spot"]}

If your web API receives loosely structured JSON objects from clients, you can deserialize the request body to a Newtonsoft.Json.Linq.JObject type.

public void Post(JObject person)
{
string name = person["Name"].ToString();
int age = person["Age"].ToObject<int>();
}

However, it is usually better to use strongly typed data objects. Then you don't need to parse the data yourself, and you get the benefits of model validation.

The XML serializer does not support anonymous types or JObject instances. If you use these features for your JSON data, you should remove the XML formatter from the pipeline, as described later in this article.

XML Media-Type Formatter

XML formatting is provided by the XmlMediaTypeFormatter class. By default, XmlMediaTypeFormatter uses the DataContractSerializer class to perform serialization.

If you prefer, you can configure the XmlMediaTypeFormatter to use the XmlSerializer instead of the DataContractSerializer. To do so, set the UseXmlSerializer property to true:

JSON and XML Serialization in ASP.NET Web API的更多相关文章

  1. 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化

    谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...

  2. Professional C# 6 and .NET Core 1.0 - Chapter 42 ASP.NET Web API

    本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处: -------------------------------------------------------- ...

  3. ASP.NET WEB API 返回JSON 出现2个双引号问题

    前言          在使用ASP.NET WEB API时,我想在某个方法返回JSON格式的数据,于是首先想到的就是手动构建JSON字符串,如:"{\"result\" ...

  4. 既生瑜何生亮?ASP.NET MVC VS ASP.NET Web API

    Asp.net MVC 与 Asp.net Web API 区别 在我们开发一些web应用时,我们一样可以在MVC Framework 中使用JsonResult 来返回JSON数据,同样也可以处理一 ...

  5. Asp.net MVC 与 Asp.net Web API 区别

    Asp.Net Web API VS Asp.Net MVC 1.Asp.net MVC 是用来创建返回视图(Views)与数据的Web应用,而Asp.net Web API是一种简单轻松地成熟的HT ...

  6. [转帖]Asp.net MVC 与 Asp.net Web API 区别

    Asp.net MVC 与 Asp.net Web API 区别 https://www.cnblogs.com/viktor988/ https://www.cnblogs.com/terry283 ...

  7. 8 种提升 ASP.NET Web API 性能的方法

    ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...

  8. ASP.NET Web API 提升性能的方法实践

    ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...

  9. 六种简单方法提升ASP.NET Web API性能

    ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...

随机推荐

  1. vue下登录页背景图上下空白处自适应等高

    遇到需求,登录页面需要顶部和底部上下等高,并且随着浏览器自适应上下高度. 解决方法: vue界面的data中先定义 data() { return { windowHeight: "&quo ...

  2. Elasticsearch.js 发布 —— 在Node.js和浏览器中调用Elasticsearch(1)

    继PHP.Ruby.Python和Perl之后,Elasticsearch最近发布了Elasticsearch.js,Elasticsearch的JavaScript客户端库.可以在Node.js和浏 ...

  3. CanvasRenderingContext2D.imageSmoothingEnabled

    https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/imageSmoothingEnabled 这是一个 ...

  4. TensorFlow学习笔记(一)--windows系统安装配置

    1.关于Tensorflow 国际惯例,先来个总体的简要介绍,摘自一个很强大的TensorFlow中文学习网站(http://www.tensorfly.cn/)的简介 TensorFlow™ 是一个 ...

  5. mysql的相关信息

    mysql数据库优化技巧 表的设计合理(字段合理,符合3NF) 添加适当索引(index)[主要4种:普通索引,主键索引,唯一索引unique,全文索引] 分表技术(水平分表->拆分表结构,垂直 ...

  6. KDDCUP CTR预测比赛总结

    赛题与数据介绍 给定查询和用户信息后预测广告点击率 搜索广告是近年来互联网的主流营收来源之一.在搜索广告背后,一个关键技术就是点击率预测-----pCTR(predict the click-thro ...

  7. CCTV-2《遇见大咖》专访雷军----笔记记录

    与央视记者约好两点采访,但因为公司会议拖到了三点.雷军对此表示抱歉,解释了一天的行程,并说:“今天不算密的,密的平均一天应该有十一个会.然后我现在基本每天中午饭,大概就是三分钟的时间.” 因为要上镜, ...

  8. vim符号列表

    Exuberant Ctags工具安装 • 软件简介 Ctags generates an index (or tag) file of language objects found in sourc ...

  9. appium 中手势密码的定位坐标

    原文地址http://www.cnblogs.com/smallTestKK/p/5408143.html 1.press方法中的坐标为绝对坐标,moveTO方法中的坐标都是相对坐标,具体来说第一个m ...

  10. 在建立与服务器的连接时出错。在连接到 SQL Server 2005 时,在默认的设置下 SQL Server 不允许进行远程连

    在建立与服务器的连接时出错.在连接到 SQL Server 2005 时,在默认的设置下 SQL Server 不允许进行远程连 sql server服务器sqlserver远程连接数据库防火墙在建立 ...