在wcf中返回原始json(字符串)

在wcf中返回原始json(字符串),wcf,json,Wcf,Json,我想构建自己的JSON,并让服务返回一个字符串,下面是代码 [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] public string GetCurrentCart() { //Code ommited string jsonClient = null; var j =

我想构建自己的JSON,并让服务返回一个字符串,下面是代码

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
public string GetCurrentCart()
{
    //Code ommited
    string jsonClient = null;
    var j = new { Content = response.Content, Display=response.Display, SubTotal=response.SubTotal};
    var s = new JavaScriptSerializer();
    jsonClient = s.Serialize(j);
    return jsonClient;
}
我得到的响应包含c#中字符串中的\“used to create”

以下是回应

"{\"Content\":\"\\r\\n\\u003cdiv\\u003e\\r\\n\\u003cinput type=\\\"hidden\\\" name=\\\"__VIEWSTATE\\\" id=\\\"__VIEWSTATE\\\" value=\\\"\/wEPDwUBMA9kFgJmD2QWAmYPZBYGAgMPFgIeBFRleHQFKFlvdSBoYXZlIG5vIGl0ZW1zIGluIHlvdXIgc2hvcHBpbmcgY2FydC5kAgUPFgIeB1Zpc2libGVoZAIHDxQrAAIPFgIfAWhkZGQYAQUMY3RsMDEkbHZDYXJ0D2dkoWijqBUJaUxmDgFrkGdWUM0mLpgQmTOe8R8hc8bZco4=\\\" \/\\u003e\\r\\n\\u003c\/div\\u003e\\r\\n\\r\\n\\u003cdiv class=\\\"block block-shoppingcart\\\"\\u003e\\r\\n    \\u003cdiv class=\\\"title\\\"\\u003e\\r\\n        \\u003cspan\\u003eShopping Cart\\u003c\/span\\u003e\\r\\n    \\u003c\/div\\u003e\\r\\n    \\u003cdiv class=\\\"clear\\\"\\u003e\\r\\n    \\u003c\/div\\u003e\\r\\n    \\u003cdiv class=\\\"listbox\\\"\\u003e\\r\\n        You have no items in your shopping cart.\\r\\n        \\r\\n        \\r\\n    \\u003c\/div\\u003e\\r\\n\\u003c\/div\\u003e\\r\\n\",\"Display\":\"You have no items in your shopping cart.\",\"SubTotal\":null}"
值的编码正确,但json本身的格式不正确。这些都是导致它变得古怪的原因


如何返回字符串而不在“'s?

当前您的web方法返回一个
字符串
以及
ResponseFormat=WebMessageFormat.Json
。它遵循字符串的JSON编码。对应于www.json.org,字符串中的所有双引号将使用反斜杠转义。因此,您目前有双重JSON编码

返回任何类型数据的最简单方法是将
GetCurrentCart()
web方法的输出类型更改为
Stream
Message
(从
System.ServiceModel.Channels
)而不是
String

有关代码示例,请参见和

因为您没有在问题中写下您使用的.NET版本,我建议您使用一种通用且最简单的方法:

public Stream GetCurrentCart()
{
    //Code ommited
    var j = new { Content = response.Content, Display=response.Display,
                  SubTotal=response.SubTotal};
    var s = new JavaScriptSerializer();
    string jsonClient = s.Serialize(j);
    WebOperationContext.Current.OutgoingResponse.ContentType =
        "application/json; charset=utf-8";
    return new MemoryStream(Encoding.UTF8.GetBytes(jsonClient));
}

我尝试了Oleg建议的方法,但发现当我对大量数据使用此方法时,会在JSON字符串的末尾追加null关键字

示例:用于包含大量数据的json {“JsonExample”:“xxxxx”}null

在以下位置找到解决此问题的解决方案: 编写了以下函数,该函数将接受一个对象并返回一个纯Json输出。因此,在main方法中返回我的对象之前,我调用下面的方法

  public HttpResponseMessage ReturnPureJson(object responseModel)
    {
        HttpResponseMessage response = new HttpResponseMessage();

        string jsonClient = Json.Encode(responseModel);
        byte[] resultBytes = Encoding.UTF8.GetBytes(jsonClient);
        response.Content = new StreamContent(new MemoryStream(resultBytes));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");

        return response;
    }
太棒了(Oleg回应) 所有这些都要确保你添加了一行 WebOperationContext.Current.OutgoingResponse.ContentType=“应用程序/json;字符集=utf-8”

如果您删除了它,结果将作为文件下载

我建议使用库来序列化JSON对象或动态对象(ExpandoObject)

在我的例子中,它将避免一些空值问题,比如总是从
JsonConvert.SerializeXXX
获取“{}”,并从
JavaScriptSerializer
将{aa:bb}扩展到{key:aa,value:bb}

完整样本如下

界面:

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "json/GetCurrentCart")]
Stream GetCurrentCart(MyRequestParam Param);
public Stream GetCurrentCart(MyRequestParam Param)
{
    //code omitted
    dynamic j = new System.Dynamic.ExpandoObject();
    j.Content = response.Content;
    j.Display = response.Display; 
    j.SubTotal = response.SubTotal;
    string s = Jil.JSON.SerializeDynamic(j);
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
    return new MemoryStream(Encoding.UTF8.GetBytes(s));
} 
实施:

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "json/GetCurrentCart")]
Stream GetCurrentCart(MyRequestParam Param);
public Stream GetCurrentCart(MyRequestParam Param)
{
    //code omitted
    dynamic j = new System.Dynamic.ExpandoObject();
    j.Content = response.Content;
    j.Display = response.Display; 
    j.SubTotal = response.SubTotal;
    string s = Jil.JSON.SerializeDynamic(j);
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
    return new MemoryStream(Encoding.UTF8.GetBytes(s));
} 

当我设置ResponseFormat=WebMessageFormat.Xml时,'s不见了,但是因为根Xml节点在那里(我不想要它)。我在这上面浪费了几个小时。谢谢嗨,奥列格,非常感谢你。我浪费了这么多的时间,终于找到了这个链接。真的非常感谢你…@Victor:我很高兴听到(阅读)我能帮助你。不客气!您好,我还有一个问题,当我返回json字符串时,最后显示空值,您可以引用此链接一次吗?请如何解决此问题,结束它附加的数组,但您不能使用HttpResponseMessage,除非您有.NET 4.5