How do I return clean JSON from a WCF Service? How do I return clean JSON from a WCF Service? json json

How do I return clean JSON from a WCF Service?

Change the return type of your GetResults to be List<Person>.
Eliminate the code that you use to serialize the List to a json string - WCF does this for you automatically.

Using your definition for the Person class, this code works for me:

public List<Person> GetPlayers(){    List<Person> players = new List<Person>();    players.Add(new  Person { FirstName="Peyton", LastName="Manning", Age=35 } );    players.Add(new  Person { FirstName="Drew", LastName="Brees", Age=31 } );    players.Add(new  Person { FirstName="Brett", LastName="Favre", Age=58 } );    return players;}


[{"Age":35,"FirstName":"Peyton","LastName":"Manning"},   {"Age":31,"FirstName":"Drew","LastName":"Brees"},   {"Age":58,"FirstName":"Brett","LastName":"Favre"}]

(All on one line)

I also used this attribute on the method:

[WebInvoke(Method = "GET",           RequestFormat = WebMessageFormat.Json,           ResponseFormat = WebMessageFormat.Json,           UriTemplate = "players")]

WebInvoke with Method= "GET" is the same as WebGet, but since some of my methods are POST, I use all WebInvoke for consistency.

The UriTemplate sets the URL at which the method is available. So I can do a GET on http://myserver/myvdir/JsonService.svc/players and it just works.

Also check out IIRF or another URL rewriter to get rid of the .svc in the URI.

If you want nice json without hardcoding attributes into your service classes,

use <webHttp defaultOutgoingResponseFormat="Json"/> in your behavior config

This is accomplished in web.config for your webservice. Set the bindingBehavior to <webHttp> and you will see the clean JSON. The extra "[d]" is set by the default behavior which you need to overwrite.

See in addition this blogpost: