How can I return json from my WCF rest service (.NET 4), using Json.Net, without it being a string,

Posted by Samuel Meacham on Stack Overflow See other posts from Stack Overflow or by Samuel Meacham
Published on 2010-06-11T23:51:58Z Indexed on 2010/06/12 1:13 UTC
Read the original article Hit count: 463

Filed under:
|
|
|

The DataContractJsonSerializer is unable to handle many scenarios that Json.Net handles just fine when properly configured (specifically, cycles).

A service method can either return a specific object type (in this case a DTO), in which case the DataContractJsonSerializer will be used, or I can have the method return a string, and do the serialization myself with Json.Net. The problem is that when I return a json string as opposed to an object, the json that is sent to the client is wrapped in quotes.

Using DataContractJsonSerializer, returning a specific object type, the response is:
{"Message":"Hello World"}

Using Json.Net to return a json string, the response is:
"{\"Message\":\"Hello World\"}"

I do not want to have to eval() or JSON.parse() the result on the client, which is what I would have to do if the json comes back as a string, wrapped in quotes. I realize that the behavior is correct; it's just not what I want/need. I need the raw json; the behavior when the service method's return type is an object, not a string.

So, how can I have my method return an object type, but not use the DataContractJsonSerializer? How can I tell it to use the Json.Net serializer instead?

Or, is there someway to directly write to the response stream? So I can just return the raw json myself? Without the wrapping quotes?

Here is my contrived example, for reference:

[DataContract]
public class SimpleMessage
{
    [DataMember]
    public string Message { get; set; }
}

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class PersonService
{
    // uses DataContractJsonSerializer
    // returns {"Message":"Hello World"}
    [WebGet(UriTemplate = "helloObject")]
    public SimpleMessage SayHelloObject()
    {
        return new SimpleMessage("Hello World");
    }

    // uses Json.Net serialization, to return a json string
    // returns "{\"Message\":\"Hello World\"}"
    [WebGet(UriTemplate = "helloString")]
    public string SayHelloString()
    {
        SimpleMessage message = new SimpleMessage() { Message = "Hello World" };
        string json = JsonConvert.Serialize(message);
        return json;
    }

    // I need a mix of the two.  Return an object type, but use the Json.Net serializer.
}

© Stack Overflow or respective owner

Related posts about wcf

Related posts about serialization