JSON and XML Serialization in ASP.NET Web API
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的更多相关文章
- 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化
谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...
- Professional C# 6 and .NET Core 1.0 - Chapter 42 ASP.NET Web API
本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处: -------------------------------------------------------- ...
- ASP.NET WEB API 返回JSON 出现2个双引号问题
前言 在使用ASP.NET WEB API时,我想在某个方法返回JSON格式的数据,于是首先想到的就是手动构建JSON字符串,如:"{\"result\" ...
- 既生瑜何生亮?ASP.NET MVC VS ASP.NET Web API
Asp.net MVC 与 Asp.net Web API 区别 在我们开发一些web应用时,我们一样可以在MVC Framework 中使用JsonResult 来返回JSON数据,同样也可以处理一 ...
- 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 ...
- [转帖]Asp.net MVC 与 Asp.net Web API 区别
Asp.net MVC 与 Asp.net Web API 区别 https://www.cnblogs.com/viktor988/ https://www.cnblogs.com/terry283 ...
- 8 种提升 ASP.NET Web API 性能的方法
ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...
- ASP.NET Web API 提升性能的方法实践
ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...
- 六种简单方法提升ASP.NET Web API性能
ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...
随机推荐
- mysql 下数据库升级脚本的编写
1 升级时必须得存储过程 /**/ drop procedure if exists pro_upgrade; DELIMITER // CREATE DEFINER=`root`@`%` PROCE ...
- 剑指Offer——和为S的两个数字
题目描述: 输入一个递增排序的数组和一个数字S,在数组中查找两个数,是的他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的. 输入描述: 对应每个测试案例,输出两个数,小的先输出. ...
- Aggregated Counting-----hdu5439(2015 长春网络赛 找规律)
#include<stdio.h> #include<string.h> #include<iostream> #include<math.h> #in ...
- 七个可以提升python程序性能的好习惯,你知道吗?
掌握一些技巧,可尽量提高Python程序性能,也可以避免不必要的资源浪费.今天就为大家带来七个可以提升python程序性能的好习惯,赶快来学习吧:. 1.使用局部变量 尽量使用局部变量代替全局变量:便 ...
- HALCON里面的一维测量。
第一步:将图片导入, 拿到图片的名字 和窗口的句柄 第二步:创建一个测量区域.这个测量区域是一个矩形,假设他的名字叫A gen_measure_rectangle2 (TmpCtrl_Row,//输入 ...
- MyBatisPartA
(正在补充) 1.从第一个程序开始,通过mybatis实现数据库表内容的增删改查 (源码zip包) 1.0准备工作 建数据库mybatis,在其中创建表sql语句如下: ; -- ---------- ...
- 2016-2017 National Taiwan University World Final Team Selection Contest A - Hacker Cups and Balls
题目: Dreamoon likes algorithm competitions very much. But when he feels crazy because he cannot figur ...
- Codeforces Round #425 (Div. 2) C - Strange Radiation
地址:http://codeforces.com/contest/832/problem/C 题目: C. Strange Radiation time limit per test 3 second ...
- Gym - 100548H The Problem to Make You Happy 2014-2015 ACM-ICPC, Asia Xian Regional Contest (BFS+博弈)
题意:Bob和Alice在一张有向无环图上移动,给定二者的起点,Bob先手.Bob的失败条件是不能移动或者与Alice相遇.两个人都采取最优策略,求Bob是否会赢 分析:银牌题.先确定所有的失败状态, ...
- How can For each...
Answer: I understand the IEnumerator/IEnumerable methods and properties and also how they are inte ...