Strongly Typed JSON

Topics: Web Api
Aug 30, 2011 at 8:06 AM
Edited Aug 30, 2011 at 8:07 AM

Hi,

Today, WCF Web API returns an array of anonymous type as JSON response.

 

  [{"Id":1,"Name":"First Contact"},{"Id":2,"Name":"Second Contact"},{"Id":3,"Name":"Third Contact"},{"Id":4,"Name":"Fourth Contact"}]

 

 Is it possible to return array of strong type like -

"contacts" :  [{"Id":1,"Name":"First Contact"},{"Id":2,"Name":"Second Contact"},{"Id":3,"Name":"Third Contact"},{"Id":4,"Name":"Fourth Contact"}]

 

 

 I have tried KnownType but it hasn't helped.

 

 

 

 

 

Aug 30, 2011 at 2:37 PM
Edited Aug 30, 2011 at 2:39 PM

You can use Json.NET with a custom MediaTypeFormatter and make use of the "TypeNameHandling" feature.

http://james.newtonking.com/archive/2010/08/13/json-net-3-5-release-8-3-5-final.aspx

Also, attributes like shown in the link above aren't needed to do this. You can simply set the property on your JsonSerializer ctor.

return new JsonSerializer
                {
                    MissingMemberHandling = MissingMemberHandling.Ignore,
                    ObjectCreationHandling = ObjectCreationHandling.Replace,
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    TypeNameHandling = TypeNameHandling.Objects
                };
Sep 7, 2011 at 10:41 AM

Hi,

I tried this option. But the output is not what I am expecting.

JSONNet is returning me this output -

[{"$id":"1","$type":"RESTEmptyWebApp.Contact, RESTEmptyWebApp","Name":"First Contact","Id":1},{"$id":"2","$type":"RESTEmptyWebApp.Contact, RESTEmptyWebApp","Name":"Second Contact","Id":2},{"$id":"3","$type":"RESTEmptyWebApp.Contact, RESTEmptyWebApp","Name":"Third Contact","Id":3},{"$id":"4","$type":"RESTEmptyWebApp.Contact, RESTEmptyWebApp","Name":"Fourth Contact","Id":4}]

RESTEmptyWebApp is name of my project. Instead of having an additional $type key, I wanted to have the Object Name as an enclosure for array.

Like

"contacts" :  [{"Id":1,"Name":"First Contact"},{"Id":2,"Name":"Second Contact"},{"Id":3,"Name":"Third Contact"},{"Id":4,"Name":"Fourth Contact"}]

As can be seen, actual array is kept just as it would have served from default JSONhandler. In addition to that I just need "contacts" as enclosure for preceding array.

How to achieve this?

Thanks.