Is there any way to control JSON formatting with the WCF Web API?
-
28-04-2021 - |
Question
With the upcoming WCF Web API, is there any way to control JSON output?
I'd like to change the casing and perhaps suppress that certain properties are included when a class is being serialized.
As an example, consider this very simply class:
[XmlRoot("catalog", Namespace = "http://api.247e.com/catalog/2012")]
public class Catalog
{
[XmlArray(ElementName = "link-templates")]
public LinkTemplate[] LinkTemplates { get; set; }
}
As you can see, I've added various XML attributes to it in order to control how it's serialized in XML. Can I do the same (or something else) for JSON?
For reference, here's a sample output in XML:
<catalog xmlns="http://api.247e.com/catalog/2012"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<link-templates>
<link-template href="http://localhost:9000/search/?criterion={criterion}"
rel="http://docs.247e.com/rels/search"/>
</link-templates>
</catalog>
For JSON, the equivalent result is this:
{
"LinkTemplates":
[
{
"Href":"http:\/\/localhost:9000\/search\/?criterion={criterion}",
"Rel":"http:\/\/docs.247e.com\/rels\/search"
}
]
}
However, I'd like to change the casing of the properties, so I'd prefer something like this instead:
{
"linkTemplates":
[
{
"href":"http:\/\/localhost:9000\/search\/?criterion={criterion}",
"rel":"http:\/\/docs.247e.com\/rels\/search"
}
]
}
A way to strip away certain class properties would also be nice.
Solution
The WCF Web API used the DataContractJsonSerializer by default to return a resource in a JSON format. So you should be using the DataContract and DataMember attributes on you class to shape the JSON result.
[DataContract]
public class Book
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "author")]
public string Author { get; set; }
[XmlIgnore] // Don't send this one
public string ImageName { get; set; }
}
OTHER TIPS
Try using the JSON.NET Formatter from the WCF Web API Contrib project on codeplex. Attributes like shown here should help you https://json.svn.codeplex.com/svn/trunk/Doc/SerializationAttributes.html
JSON.NET has several attribute options which can control what is serialized and how. http://james.newtonking.com/projects/json/help/