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 ...
随机推荐
- mysqldump备份成压缩包
可以直接应用mysqldump直接将mysql数据库中的表或者整个数据库备份成压缩格式的包 废话不多说了直接上代码吧 mysqldump -h localhost -uroot -pHb118114 ...
- Linux Shell 文本处理工具集锦--Awk―sed―cut(row-based, column-based),find、grep、xargs、sort、uniq、tr、cut、paste、wc
本文将介绍Linux下使用Shell处理文本时最常用的工具:find.grep.xargs.sort.uniq.tr.cut.paste.wc.sed.awk:提供的例子和参数都是最常用和最为实用的: ...
- Mustache 中的html转义问题处理
避免在使用Mustache引擎是发生html字符转义 1,模板代码示例: var xml= " <?xml version="1.0" encoding=&q ...
- MySQL和时间戳有关的函数
1. MySQL 获得当前时间戳函数:current_timestamp, current_timestamp()mysql> select current_timestamp, current ...
- What’s wrong with virtual methods called through an interface
May 31, 2016 Calling a virtual method through an interface always was a lot slower than calling a st ...
- MySql库、表权限管理
#授权表user #该表放行的权限,针对:所有数据,所有库下所有表,以及表下的所有字段db #该表放行的权限,针对:某一数据库,该数据库下的所有表,以及表下的所有字段tables_priv #该表放行 ...
- MySQL行(记录)的详细操作
一 介绍 MySQL数据操作: DML ======================================================== 在MySQL管理软件中,可以通过SQL语句中的 ...
- Android在使用WebView时,通过Javascript调用JAVA函数
webView = (WebView) findViewById(R.id.article_webview); //WebView启用Javascript脚本运行 webView.getSetting ...
- Java编程:将具有父子关系的数据库表数据转换为树形结构,支持无限层级
在平时的开发工作中,经常遇到这样一个场景,在数据库中存储了具有父子关系的数据,需要将这些数据以树形结构的形式在界面上进行展示.本文的目的是提供了一个通用的编程模型,解决将具有父子关系的数据转换成树形结 ...
- 007-Hadoop Hive sql语法详解2-修改表结构
一.表 更改表名:ALTER TABLE table_name RENAME TO new_table_name 增加表的元数据信息:ALTER TABLE table_name SET TBLPRO ...