简体   繁体   中英

Why is my Json string response escaped for a WCF Rest web service (weakly-typed Json) response?

I have this contract :

[ServiceContract]
public interface IServiceJsonContract
{
    [WebInvoke(UriTemplate = "/MyMethod", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")]
    Message MyMethod(Message input);
}

And the definition for MyMethod is :

Message MyMethod(Message input)
{
...
Message response = Message.CreateMessage(
                                 MessageVersion.None,
                                 "*",
                                 "{\"bla\": 2 }", 
                                 new DataContractJsonSerializer(typeof(string)));

response.Properties.Add( WebBodyFormatMessageProperty.Name,new 
WebBodyFormatMessageProperty(WebContentFormat.Json)); 

var contextOutgoingResponse = WebOperationContext.Current.OutgoingResponse;
contextOutgoingResponse.ContentType = "application/json;charset=utf-8";

return response;
}

When calling the method I got the Json escaped:

"{\\"bla\\": 2 }"

instead of unescaped one (below):

"{"bla": 2 }"

Any idea how to get the unescaped Json ( "{"bla": 2 }" ) ?

Thanks

The DataContractJsonSerializer is serializing your string and escaping the quotation marks. Create a class to hold your data and pass that instead of the string.

public class MyData 
{
    public string Bla { get; set; } 
}

// create an instance
MyData myData = new MyData()
{
    Bla = "the value";
};   

// then use it
Message response = Message.CreateMessage(
                             MessageVersion.None,
                             "*",
                             myData, 
                             new DataContractJsonSerializer(typeof(MyData)));

you can use Stream as your out put. this way you can send back uncapped string:

    [ServiceContract]
    public interface IServiceJsonContract
    {
        [WebInvoke(UriTemplate = "/MyMethod", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")]
        Stream MyMethod(Message input);
    }

Stream MyMethod(Message input)
{
..
return new MemoryStream(Encoding.UTF8.GetBytes("{\"bla\": 2 }"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM