"
ASP.NET (snapshot 2017) Microsoft documentation and samples

JSON and XML Serialization in ASP.NET Web API

by Mike Wasson

This article describes the JSON and XML formatters in ASP.NET Web API.

In ASP.NET Web API, a media-type formatter is an object that can:

Web API provides media-type formatters for both JSON and XML. The framework inserts these formatters into the pipeline by default. Clients can request either JSON or XML in the Accept header of the HTTP request.

Contents

## 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:

[!code-csharpMain]

   1:  var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
   2:  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.

[!code-csharpMain]

   1:  public class Product
   2:  {
   3:      public string Name { get; set; }
   4:      public decimal Price { get; set; }
   5:      [JsonIgnore]
   6:      public int ProductCode { get; set; } // omitted
   7:  }

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.

[!code-csharpMain]

   1:  [DataContract]
   2:  public class Product
   3:  {
   4:      [DataMember]
   5:      public string Name { get; set; }
   6:      [DataMember]
   7:      public decimal Price { get; set; }
   8:      public int ProductCode { get; set; }  // omitted by default
   9:  }

### 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:

[!code-consoleMain]

   1:  2012-07-27T18:51:45.53403Z         // UTC
   2:  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:

[!code-csharpMain]

   1:  // Convert all dates to UTC
   2:  var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
   3:  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:

[!code-csharpMain]

   1:  var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
   2:  json.SerializerSettings.DateFormatHandling 
   3:  = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;

### Indenting

To write indented JSON, set the Formatting setting to Formatting.Indented:

[!code-csharpMain]

   1:  var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
   2:  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:

[!code-csharpMain]

   1:  var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
   2:  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:

[!code-csharpMain]

   1:  public object Get()
   2:  {
   3:      return new { 
   4:          Name = "Alice", 
   5:          Age = 23, 
   6:          Pets = new List<string> { "Fido", "Polly", "Spot" } 
   7:      };
   8:  }

The response message body will contain the following JSON:

[!code-jsonMain]

   1:  {"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.

[!code-csharpMain]

   1:  public void Post(JObject person)
   2:  {
   3:      string name = person["Name"].ToString();
   4:      int age = person["Age"].ToObject<int>();
   5:  }

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:

[!code-csharpMain]

   1:  var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
   2:  xml.UseXmlSerializer = true;

The XmlSerializer class supports a narrower set of types than DataContractSerializer, but gives more control over the resulting XML. Consider using XmlSerializer if you need to match an existing XML schema.

XML Serialization

This section describes some specific behaviors of the XML formatter, using the default DataContractSerializer.

By default, the DataContractSerializer behaves as follows:

If you need more control over the serialization, you can decorate the class with the DataContract attribute. When this attribute is present, the class is serialized as follows:

### Read-Only Properties

Read-only properties are not serialized. If a read-only property has a backing private field, you can mark the private field with the DataMember attribute. This approach requires the DataContract attribute on the class.

[!code-csharpMain]

   1:  [DataContract]
   2:  public class Product
   3:  {
   4:      [DataMember]
   5:      private int pcode;  // serialized
   6:   
   7:      // Not serialized (read-only)
   8:      public int ProductCode { get { return pcode; } }
   9:  }

### Dates

Dates are written in ISO 8601 format. For example, “2012-05-23T20:21:37.9116538Z”.

### Indenting

To write indented XML, set the Indent property to true:

[!code-csharpMain]

   1:  var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
   2:  xml.Indent = true;

## Setting Per-Type XML Serializers

You can set different XML serializers for different CLR types. For example, you might have a particular data object that requires XmlSerializer for backward compatibility. You can use XmlSerializer for this object and continue to use DataContractSerializer for other types.

To set an XML serializer for a particular type, call SetSerializer.

[!code-csharpMain]

   1:  var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
   2:  // Use XmlSerializer for instances of type "Product":
   3:  xml.SetSerializer<Product>(new XmlSerializer(typeof(Product)));

You can specify an XmlSerializer or any object that derives from XmlObjectSerializer.

## Removing the JSON or XML Formatter

You can remove the JSON formatter or the XML formatter from the list of formatters, if you do not want to use them. The main reasons to do this are:

The following code shows how to remove the default formatters. Call this from your Application_Start method, defined in Global.asax.

[!code-csharpMain]

   1:  void ConfigureApi(HttpConfiguration config)
   2:  {
   3:      // Remove the JSON formatter
   4:      config.Formatters.Remove(config.Formatters.JsonFormatter);
   5:   
   6:      // or
   7:   
   8:      // Remove the XML formatter
   9:      config.Formatters.Remove(config.Formatters.XmlFormatter);
  10:  }

## Handling Circular Object References

By default, the JSON and XML formatters write all objects as values. If two properties refer to the same object, or if the same object appears twice in a collection, the formatter will serialize the object twice. This is a particular problem if your object graph contains cycles, because the serializer will throw an exception when it detects a loop in the graph.

Consider the following object models and controller.

[!code-csharpMain]

   1:  public class Employee
   2:  {
   3:      public string Name { get; set; }
   4:      public Department Department { get; set; }
   5:  }
   6:   
   7:  public class Department
   8:  {
   9:      public string Name { get; set; }
  10:      public Employee Manager { get; set; }
  11:  }
  12:   
  13:  public class DepartmentsController : ApiController
  14:  {
  15:      public Department Get(int id)
  16:      {
  17:          Department sales = new Department() { Name = "Sales" };
  18:          Employee alice = new Employee() { Name = "Alice", Department = sales };
  19:          sales.Manager = alice;
  20:          return sales;
  21:      }
  22:  }

Invoking this action will cause the formatter to thrown an exception, which translates to a status code 500 (Internal Server Error) response to the client.

To preserve object references in JSON, add the following code to Application_Start method in the Global.asax file:

[!code-csharpMain]

   1:  var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
   2:  json.SerializerSettings.PreserveReferencesHandling = 
   3:      Newtonsoft.Json.PreserveReferencesHandling.All;

Now the controller action will return JSON that looks like this:

[!code-jsonMain]

   1:  {"$id":"1","Name":"Sales","Manager":{"$id":"2","Name":"Alice","Department":{"$ref":"1"}}}

Notice that the serializer adds an “$id&quot; property to both objects. Also, it detects that the Employee.Department property creates a loop, so it replaces the value with an object reference: {&quot;$ref”:“1”}.

[!NOTE] Object references are not standard in JSON. Before using this feature, consider whether your clients will be able to parse the results. It might be better simply to remove cycles from the graph. For example, the link from Employee back to Department is not really needed in this example.

To preserve object references in XML, you have two options. The simpler option is to add [DataContract(IsReference=true)] to your model class. The IsReference parameter enables object references. Remember that DataContract makes serialization opt-in, so you will also need to add DataMember attributes to the properties:

[!code-csharpMain]

   1:  [DataContract(IsReference=true)]
   2:  public class Department
   3:  {
   4:      [DataMember]
   5:      public string Name { get; set; }
   6:      [DataMember]
   7:      public Employee Manager { get; set; }
   8:  }

Now the formatter will produce XML similar to following:

[!code-xmlMain]

   1:  <Department xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" 
   2:              xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" 
   3:              xmlns="http://schemas.datacontract.org/2004/07/Models">
   4:    <Manager>
   5:      <Department z:Ref="i1" />
   6:      <Name>Alice</Name>
   7:    </Manager>
   8:    <Name>Sales</Name>
   9:  </Department>

If you want to avoid attributes on your model class, there is another option: Create a new type-specific DataContractSerializer instance and set preserveObjectReferences to true in the constructor. Then set this instance as a per-type serializer on the XML media-type formatter. The following code show how to do this:

[!code-csharpMain]

   1:  var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
   2:  var dcs = new DataContractSerializer(typeof(Department), null, int.MaxValue, 
   3:      false, /* preserveObjectReferences: */ true, null);
   4:  xml.SetSerializer<Department>(dcs);

## Testing Object Serialization

As you design your web API, it is useful to test how your data objects will be serialized. You can do this without creating a controller or invoking a controller action.

[!code-csharpMain]

   1:  string Serialize<T>(MediaTypeFormatter formatter, T value)
   2:  {
   3:      // Create a dummy HTTP Content.
   4:      Stream stream = new MemoryStream();
   5:      var content = new StreamContent(stream);
   6:      /// Serialize the object.
   7:      formatter.WriteToStreamAsync(typeof(T), value, stream, content, null).Wait();
   8:      // Read the serialized string.
   9:      stream.Position = 0;
  10:      return content.ReadAsStringAsync().Result;
  11:  }
  12:   
  13:  T Deserialize<T>(MediaTypeFormatter formatter, string str) where T : class
  14:  {
  15:      // Write the serialized string to a memory stream.
  16:      Stream stream = new MemoryStream();
  17:      StreamWriter writer = new StreamWriter(stream);
  18:      writer.Write(str);
  19:      writer.Flush();
  20:      stream.Position = 0;
  21:      // Deserialize to an object of type T
  22:      return formatter.ReadFromStreamAsync(typeof(T), stream, null, null).Result as T;
  23:  }
  24:   
  25:  // Example of use
  26:  void TestSerialization()
  27:  {
  28:      var value = new Person() { Name = "Alice", Age = 23 };
  29:   
  30:      var xml = new XmlMediaTypeFormatter();
  31:      string str = Serialize(xml, value);
  32:   
  33:      var json = new JsonMediaTypeFormatter();
  34:      str = Serialize(json, value);
  35:   
  36:      // Round trip
  37:      Person person2 = Deserialize<Person>(json, str);
  38:  }



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/formats-and-model-binding/json-and-xml-serialization.htm
< THANKS ME>