我有这份合同:
[ServiceContract]
public interface IServiceJsonContract
{
[WebInvoke(UriTemplate = "/MyMethod", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")]
Message MyMethod(Message input);
}
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;
}
调用方法时,我得到了Json转义:
“{\”bla \“:2}”
而不是未转义的(下方):
“{”bla“:2}”
知道如何获得未转义的Json(“{”bla“:2}”)?
由于
答案 0 :(得分:0)
DataContractJsonSerializer正在序列化您的字符串并转义引号。创建一个类来保存数据并传递它而不是字符串。
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)));
答案 1 :(得分:0)
您可以使用Stream
作为输出。这样你就可以发回无上限的字符串:
[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 }"));
}