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. BitCoin Trading Strategies BackTest With PyAlgoTrade

    Written by Khang Nguyen Vo, khangvo88@gmail.com, for the RobustTechHouse blog. Khang is a graduate f ...

  2. ledecode Reverse Words in a String III

    557. Reverse Words in a String III Given a string, you need to reverse the order of characters in ea ...

  3. Power Strings----poj2406(kmp扩展 循环节)

    题目链接:http://poj.org/problem?id=2406 题意:就是求串s能够最多由多少个相同的串a串联而成: 例如 ababab 由3个ab串联而成: abababa 只能由1个aba ...

  4. MySQL优化(二):SQL优化

    一.SQL优化 1.优化SQL一般步骤 1.1 查看SQL执行频率 SHOW STATUS LIKE 'Com_%'; Com_select:执行SELECT操作的次数,一次查询累加1.其他类似 以下 ...

  5. Flask之视图函数

    视图示例 @app.route('/hello') def hello(): return 'Hello World' if __name__ == '__main__': app.run() 特殊的 ...

  6. git学习------>从SVN迁移到Git之后,项目开发代码继续在SVN提交,如何同步迁移之后继续在SVN提交的代码到Git?

    最近逐步逐步的将公司的项目都从SVN往Git迁移了,但是想团队成员都能够一步到位就迁移到Git是不可能的,因为还有大部分人都还不会Git,所以整个过渡过程估计得大半年. 因此导致虽然项目迁移过来了,但 ...

  7. Linux cd命令 pwd命令

    1.cd命令 cd:及Change Directory改变目录的意思,用于更改到指定的目录 用法:cd [目录] 其中 "."代表当前目录,".."代表当前目录 ...

  8. python 学习笔记(十四)有依赖关系的接口开发

    接口开发中存在很多有依赖关系的接口,例如:BBS中发帖的时候就需要进行校验用户是否登录,那么此时发帖的接口就与用户登录接口有依赖关系.在发帖时就需要先获取用户的session,与当前登录用户进行校验对 ...

  9. maven+springmvc+spring+mybatis

    一.项目搭建 1)创建maven项目 选择apache的maven-archetype-webapp 填入groupID : 例如 com.mracale artifactId :例如 shoppin ...

  10. Java中的并发编程集合使用

    一.熟悉Java自带的并发编程集合 在java.util.concurrent包里有很多并发编程的常用工具类. package com.ietree.basicskill.mutilthread.co ...