[英]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 : MyMethod的定义是:
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: 在调用方法时,我得到了Json转义:
"{\\"bla\\": 2 }" “{\\”bla \\“:2}”
instead of unescaped one (below): 而不是未转义的(下方):
"{"bla": 2 }" “{”bla“:2}”
Any idea how to get the unescaped Json ( "{"bla": 2 }" ) ? 知道如何获得未转义的Json(“{”bla“:2}”)?
Thanks 谢谢
The DataContractJsonSerializer is serializing your string and escaping the quotation marks. DataContractJsonSerializer正在序列化您的字符串并转义引号。 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. 你可以使用
Stream
作为你的输出。 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 }"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.