Asp. Net Web API 2 Lesson 13th -- JSON and XML serialization in ASP. NET Web API

Source: Internet
Author: User
Tags iso 8601 iso 8601 format

Before reading this article, you can also go to the Asp. Net Web API 2 series navigation to view http://www.cnblogs.com/aehyok/p/3446289.html

This document describes the JSON and XML formatters in ASP. NET Web APIs.

In ASP. NET Web APIs,Media-type Formatter)Is an object that can do the following:

  • Read CLR (runtime in Common Language) objects from HTTP message bodies
  • Write the CLR object to the HTTP message body

Web API provides a media Formatter for JSON and XML. The Framework has inserted these formatters into the message processing pipeline by default. The client can request JSON or XML in the HTTP request's Accept header.

JSON format is composedJsonMediaTypeFormatterClass. By default,JsonMediaTypeFormatterUse the Json. NET Library to perform serialization. Json. NET is a third-party open-source project.

If you like it, you canJsonMediaTypeFormatterConfigure to useDataContractJsonSerializerTo replace Json. NET. To do this, you only needUseDataContractJsonSerializerSet the attributeTrueYou can:

 json == ;
JSON serialization

This section describes some specific behaviors of the Json formatter when the default JSON. NET serializer is used. This does not mean to include the entire document of the Json. NET Library. For more information, see Json. NET Documentation.

What will be serialized?

By default, all public attributes and fields are included in serialized JSON. To ignore an attribute or field, you must useJsonIgnoreModify the annotation attribute.

   Name { ;   Price { ;   ProductCode { ; ; } }

If you prefer the opt-in method, you can useDataContractAnnotation attribute to modify the class. If the annotation attribute exists, all members are ignored unlessDataMember.DataMemberYou can also serialize private members.

   Name { ;   Price { ;   ProductCode { ; ; }  }
Read-only attribute

The read-only attribute is serialized by default.

Dates (date)

By default, Json. NET writes the date in ISO 8601 format. A date written in UTC (Coordinated Universal Time-World Standard Time) format is suffixed with "Z ". The date in the local time format includes a Time Zone offset. For example:

--27T18::.53403Z         --27T11::-:    

By default, Json. NET retains the time zone. You can override this line by setting the DateTimeZoneHandling attribute:

 json ==

If you prefer to use Microsoft's JSON Date Format ("\/Date (ticks) \/") instead of ISO 8601, you can set it on SerializerSettingsDateFormatHandlingAttribute:

 json ==
Indenting)

To write the Indented JSON, you canFormattingSetFormatting. Indented:

 json ==
Camel Casing (Camel case conversion)

In order to convert the JSON attribute name in case-insensitive mode without modifying the data model, you can set the attribute nameCamelCasePropertyNamesContractResolver:

 json ==      CamelCasePropertyNamesContractResolver();
Anonymous and weak type objects

Action method or return an anonymous object and serialize it to JSON. For example:

  = = =  List<> { , , 

The response body will contain the following JSON:

{:,:,:[,,]}

If the Web API receives JSON with a loose structure from the client, you can serialize the Request bodyNewtonsoft. Json. Linq. JObjectType.

  name = person[ age = person[].ToObject<>

However, it is usually better to use a strong data object. Therefore, you do not need to parse the data and obtain the benefits of model verification.

The XML serializer does not support the anonymous type orJObjectInstance. If you use these features for JSON data, you should remove the XML formatter in the pipeline, as described later in this article.

XML format is composedXmlMediaTypeFormatterClass. By default,XmlMediaTypeFormatterUseDataContractSerializerClass to execute serialization. If you like it, you canXmlMediaTypeFormatterConfigure to useXmlSerializerInstead of DataContractSerializer. To do this, you canUseXmlSerializerSet propertyTrue:

 xml == ;

XmlSerializerType set supported by the classDataContractSerializerIt is narrower, but it has more control over the result XML. If you need to match the existing XML Scheme, consider usingXmlSerializer.

XML Serialization -- XML Serialization

This section describes how to use the defaultDataContractSerializerSome special actions of the XML formatter. By default, DataContractSerializer acts as follows:

  • Serialize all public read/write attributes and fields. To ignore an attribute or field, useIgnoreDataMemberModify the annotation attribute.
  • Private and protected members are not sequential.
  • Read-Only attributes are not serialized
  • The class name and member name are written to XML according to the exact representation in the class declaration.
  • Use the default namespace of XML

If you need more control over serialization, you can useDataContractAnnotation attribute modifier class. When this annotation property appears, the class is serialized as a policy:

  • "Opt in" method: attributes and fields are not serialized by default. To serialize an attribute or field, useDataMemberModify the annotation attribute.
  • To serialize private or protected members, useDataMemberModify the annotation attribute.
  • Read-Only attributes are not serialized.
  • To change the class name rendering in XML, goDataContractSet in Annotation PropertiesNameParameters.
  • To change the rendering of the member name in XML, SetDataMemberIn the annotation attributeNmaeParameters.
  • To change the XML namespace, SetDataContractClassNamespaceParameters.

 

Read-Only Properties -- Read-Only Properties

Read-Only attributes are not serialized. If the read-only attribute supports a private field, you can useDataMemberThe annotation property marks this private field. This method needs to be used on the classDataContractAnnotation property.

   pcode;        ProductCode {  { 
Dates -- Date

The date is written in ISO 8601 format. For example, "2012-05-23T20: 21: 37.9116538Z ".

Indenting -- indent

To write the indent XML, SetIndentSet propertyTrue:

 xml == ; 
Set the XML serializer for each Type (Per-Type)

You can set different XML serializer for different CLR types. For example, you may have a special data object, which is required for backward compatibility.XmlSerializer. You can useXmlSerializerFor other types, continue to useDataContractSerializer.

To set the XML serializer for special types, you must callSetSerializer.

 xml =xml.SetSerializer<Product>( XmlSerializer((Product)));

You can specifyXmlSerializer, Or any derived fromXmlObjectSerializer.

Remove the JSON or XML formatter

You can delete the JSON formatter or XML formatter from the formatter list, as long as you do not want to use them. The main reason for doing so is:

  • Restrict your Web API response to a specific media type. For example, you may decide to only support JSON responses and delete the XML formatter.
  • Use a custom formatter to replace the default formatter. For example, you may use your own custom JSON formatter to replace the (default) JSON formatter.

The following code deletes the default formatter. Defined in Global. asaxApplication_StartMethod.

 

By default, the JSON and XML formatters write all objects as values. If two attributes reference the same object, or if the same object appears twice in a collection, the formatter serializes the object twice. This is a special problem that occurs when the object graph contains loops, because the serializer throws an exception when detecting loops in the object graph.

Consider the following object model and controller.

   Name { ;  Department Department { ;    Name { ;  Employee Manager { ;   Department Get(=  Department() { Name = =  Employee() { Name = , Department ==

Calling this action triggers the formatter to throw an exception, which is converted into a status code 500 (internal server error) Response sent to the client.

To retain the object reference in JSONApplication_StartMethod To Add the following code:

 json ==

Now, this controller action returns a JSON format similar to the following:

{:,:,:{:,:,:{:}}}

Note that the serializer adds a "$ id" to both objects ". Moreover, it detects that the Employee. Department attribute produces a loop, so it replaces this value with an object reference {"$ ref": "1.

Object references are non-standard JSON. Before using this feature, consider whether your client can parse this result. It may be better to simply remove the loops in the object graph. For example, linking the Employee to the Department in this example is not really necessary.

To retain the object reference in XML, you can use two options. A simple option is to add [DataContract (IsReference = true)] to the model class.IsReferenceThe parameter enables object reference. Remember,DataContractThis constitutes a serialized "Opt-in". Therefore, you need to add attributesDataMemberAnnotation attributes:

[DataContract(IsReference=   Name { ;  Employee Manager { ; 

Now, the formatter will generate XML similar to the following format:

<Department xmlns:i= z:Id===>    <Manager>        <Department z:Ref= />        <Name>Alice</Name>    </Manager>    <Name>Sales</Name></Department>

To avoid using annotation properties on model classes, another option is to create a new type-specificDataContractSerializerInstance, and in the constructorPreserveObjectReferencesSetTrue:

 xml = dcs =  DataContractSerializer((Department), , ,  , <Department>(dcs);

It is useful to test how to serialize objects when designing Web APIs. You can do this without creating a controller or calling a controller action.

 

 Serialize<T>    Stream stream =  content =     formatter.WriteToStreamAsync((T), value, stream, content.Headers,     stream.Position = <T>(MediaTypeFormatter formatter,  str)  T :     Stream stream = = =      formatter.ReadFromStreamAsync((T), stream, , ).Result  value =  Person() { Name = , Age =  xml =  str = json = =    Person person2 = Deserialize<Person>

This course provides a brief introduction to the serialization and deserialization of JSON and XML.

The reference link for this article is http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization

This article has also been updated to the Web API navigation series http://www.cnblogs.com/aehyok/p/3446289.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.