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 ...
随机推荐
- 解决IOS7在TableView 被导航栏挡住的BUG!!
self.edgesForExtendedLayout = UIRectEdgeNone; 就这么简单!
- TCP控制位 sendUrgentData 队列 队列元素 优先级 极限 急停 置顶
Socket (Java Platform SE 7 ) https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#sendUrge ...
- Apache Kafka源码分析 – Replica and Partition
Replica 对于local replica, 需要记录highWatermarkValue,表示当前已经committed的数据对于remote replica,需要记录logEndOffsetV ...
- SSH整合中,使用父action重构子类action类.(在父类中获取子类中的泛型对象)
import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import com.opensymphony.x ...
- SpringCloud 进阶之Ribbon和Feign(负载均衡)
1. Ribbon 负载均衡 Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端,负载均衡的工具; 1.1 Ribbon 配置初步 1.1.1 修改 micros ...
- django之页面缓存
一 全站缓存(全局缓存) 在settings中配置,主要就是两个中间件,需要注意的就是两个中间件的前后位置 MIDDLEWARE_CLASSES = ( ‘django.middleware.cac ...
- 聊聊高并发(三十四)Java内存模型那些事(二)理解CPU快速缓存的工作原理
在上一篇聊聊高并发(三十三)从一致性(Consistency)的角度理解Java内存模型 我们说了Java内存模型是一个语言级别的内存模型抽象.它屏蔽了底层硬件实现内存一致性需求的差异,提供了对上层的 ...
- Jenkins节点配置页面,启动方法没有"Launch agent via Java Web Start"解决方法?
Jenkins的配置从节点中默认没有Launch agent via JavaWeb Start,解决办法: 步骤: 1:打开"系统管理"——"Configure Glo ...
- 解决wordcloud导出图片不清楚
使用WordCloud生成词云图片 本文详细介绍参考自:https://www.jianshu.com/p/fdd0acccf1c5 wordcloud开源项目:https://github.com/ ...
- koa2+mongoose搭建框架模型
由于学的是java,所以此框架多少有点java的影子,我觉得不必排斥语言,只要思想好,所有语言均可以通用.项目分以下几层 app.js项目启动入口,类似于main函数 controller-view层 ...