JSON and XML Serialization in ASP.NET Web API - ASP.NET 4.x (2024)

  • Article

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:

  • Read CLR objects from an HTTP message body
  • Write CLR objects into an HTTP message body

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

    • Read-Only Properties
    • Dates
    • Indenting
    • Camel Casing
    • Anonymous and Weakly-Typed Objects
  • XML Media-Type Formatter

    • Read-Only Properties
    • Dates
    • Indenting
    • Setting Per-Type XML Serializers
  • Removing the JSON or XML Formatter

  • Handling Circular Object References

  • Testing Object Serialization

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 // UTC2012-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 UTCvar 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 = 23, 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:

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;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:

  • All public read/write properties and fields are serialized. To omit a property or field, decorate it with the IgnoreDataMember attribute.
  • Private and protected members are not serialized.
  • Read-only properties are not serialized. (However, the contents of a read-only collection property are serialized.)
  • Class and member names are written in the XML exactly as they appear in the class declaration.
  • A default XML namespace is used.

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:

  • "Opt in" approach: Properties and fields are not serialized by default. To serialize a property or field, decorate it with the DataMember attribute.
  • To serialize a private or protected member, decorate it with the DataMember attribute.
  • Read-only properties are not serialized.
  • To change how the class name appears in the XML, set the Name parameter in the DataContract attribute.
  • To change how a member name appears in the XML, set the Name parameter in the DataMember attribute.
  • To change the XML namespace, set the Namespace parameter in the DataContract class.

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.

[DataContract]public class Product{ [DataMember] private int pcode; // serialized // Not serialized (read-only) public int ProductCode { get { return pcode; } }}

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:

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;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.

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;// Use XmlSerializer for instances of type "Product":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:

  • To restrict your web API responses to a particular media type. For example, you might decide to support only JSON responses, and remove the XML formatter.
  • To replace the default formatter with a custom formatter. For example, you could replace the JSON formatter with your own custom implementation of a JSON formatter.

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

void ConfigureApi(HttpConfiguration config){ // Remove the JSON formatter config.Formatters.Remove(config.Formatters.JsonFormatter); // or // Remove the XML formatter config.Formatters.Remove(config.Formatters.XmlFormatter);}

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.

public class Employee{ public string Name { get; set; } public Department Department { get; set; }}public class Department{ public string Name { get; set; } public Employee Manager { get; set; }}public class DepartmentsController : ApiController{ public Department Get(int id) { Department sales = new Department() { Name = "Sales" }; Employee alice = new Employee() { Name = "Alice", Department = sales }; sales.Manager = alice; return sales; }}

Invoking this action will cause the formatter to throw 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:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;

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

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

Notice that the serializer adds an "$id" property to both objects. Also, it detects that the Employee.Department property creates a loop, so it replaces the value with an object reference: {"$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:

[DataContract(IsReference=true)]public class Department{ [DataMember] public string Name { get; set; } [DataMember] public Employee Manager { get; set; }}

Now the formatter will produce XML similar to following:

<Department xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" xmlns="http://schemas.datacontract.org/2004/07/Models"> <Manager> <Department z:Ref="i1" /> <Name>Alice</Name> </Manager> <Name>Sales</Name></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:

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;var dcs = new DataContractSerializer(typeof(Department), null, int.MaxValue, false, /* preserveObjectReferences: */ true, null);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.

string Serialize<T>(MediaTypeFormatter formatter, T value){ // Create a dummy HTTP Content. Stream stream = new MemoryStream(); var content = new StreamContent(stream); /// Serialize the object. formatter.WriteToStreamAsync(typeof(T), value, stream, content, null).Wait(); // Read the serialized string. stream.Position = 0; return content.ReadAsStringAsync().Result;}T Deserialize<T>(MediaTypeFormatter formatter, string str) where T : class{ // Write the serialized string to a memory stream. Stream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(str); writer.Flush(); stream.Position = 0; // Deserialize to an object of type T return formatter.ReadFromStreamAsync(typeof(T), stream, null, null).Result as T;}// Example of usevoid TestSerialization(){ var value = new Person() { Name = "Alice", Age = 23 }; var xml = new XmlMediaTypeFormatter(); string str = Serialize(xml, value); var json = new JsonMediaTypeFormatter(); str = Serialize(json, value); // Round trip Person person2 = Deserialize<Person>(json, str);}
JSON and XML Serialization in ASP.NET Web API - ASP.NET 4.x (2024)

FAQs

Can asp net Web API specialize to XML or JSON? ›

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.

How do I get asp net Web API to return JSON instead of XML? ›

Let's explore them:
  1. Change the default formatter for Accept: text/html to return JSON. ...
  2. Change the default formatter for Accept: text/html to return JSON, and also return a valid Content-Type: application/json header. ...
  3. Completely remove the XML formatter, forcing ASP.NET Web API to return JSON by default.
Oct 13, 2015

How to convert JSON data to XML in Web API? ›

How to convert JSON to XML
  1. connect to an API.
  2. get a JSON response with product information.
  3. convert JSON into XML.
  4. connect to SFTP.
  5. upload a file in XML format.
Jan 24, 2023

Which library is used by Web API for JSON serialization? ›

Which of the following Open-source libraries is used by WEB API for JSON serialization? Json.NET library is generally used by Web API for JSON serialization.

Which is better for API JSON or XML? ›

JSON is generally a better choice for APIs, mobile apps, and data storage, while XML is better suited for complex document structures that require data exchange.

What is the best approach for requesting JSON instead of XML from an API? ›

Final answer: To specifically request JSON from an API instead of XML, use the Accept header with the value application/json. This standardized method informs the server of the client's preferred data format.

How to convert XML response to JSON in Web API? ›

One way to do it would be to deserialize the XML into objects and then serialize them again into JSON. A more efficient (though harder to code up approach) would be to write your own xml-to-json "transcriber" that reads in the XML and spits out JSON. Just note that not all XML can be represented easily as JSON.

Is it possible to convert JSON to XML? ›

To convert a JSON document to XML, follow these steps: Select the JSON to XML action from the Tools > JSON Tools menu. Choose or enter the Input URL of the JSON document. Choose the path of the Output file that will contain the resulting XML document.

What is serialization in Web API? ›

Serialization is the process of converting a data object—a combination of code and data represented within a region of data storage—into a series of bytes that saves the state of the object in an easily transmittable form.

Does Web API return JSON by default? ›

By default, when the framework detects that the request is coming from a browser: The Accept header is ignored. The content is returned in JSON, unless otherwise configured.

How to send JSON data in Web API? ›

Here's a step-by-step guide on how to do it:
  1. Create a C# class that represents the data you want to send.
  2. Serialize the object to a JSON string using a library like Newtonsoft. ...
  3. Create an instance of HttpClient and set up the necessary headers, such as Content-Type: application/json .
Jun 20, 2024

What is the fastest JSON reader for C#? ›

Utf8Json - Fast JSON Serializer for C# Definitely Fastest and Zero Allocation JSON Serializer for C#(. NET, . NET Core, Unity and Xamarin), this serializer write/read directly to UTF8 binary so boostup performance.

What is the difference between REST API and ASP NET Web API? ›

Web APIs encompass any API using HTTP or HTTPS. All REST APIs are Web APIs, but not all Web APIs are RESTful. REST APIs are Web APIs that follow specific architectural principles like statelessness and client-server architecture. Technically, they can be stateless or stateful.

Which API uses only XML data format? ›

SOAP APIs are rigid and only allow XML messaging between applications.

What format does Web API return data in? ›

By default Web API returns result in XML format. So if our service need to support both the formats then we need to add code in WebApiConfig.

Top Articles
Net Worth By Age for Physicians | Blankinship & Foster
Customer Needs: Definition, Example, Analysis
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
Non Sequitur
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Kelle Weber

Last Updated:

Views: 6500

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Kelle Weber

Birthday: 2000-08-05

Address: 6796 Juan Square, Markfort, MN 58988

Phone: +8215934114615

Job: Hospitality Director

Hobby: tabletop games, Foreign language learning, Leather crafting, Horseback riding, Swimming, Knapping, Handball

Introduction: My name is Kelle Weber, I am a magnificent, enchanting, fair, joyous, light, determined, joyous person who loves writing and wants to share my knowledge and understanding with you.