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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3078397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:30:53  来源:igfitidea点击:

Returning raw json (string) in wcf

wcfjson

提问by Paul Knopf

I want to build my own JSON, and have the service return a string, here is the code

我想构建自己的 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;
}

The response I am getting contains the \" used to create "'s in strings in c#.

我得到的响应包含 \" 用于在 c# 中的字符串中创建 "。

The following is the response.

以下是回应。

"{\"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}"

The values are being correctly encoded, but the json itself is not properly formatted. These \'s cause it to go out of wack.

值被正确编码,但 json 本身的格式不正确。这些\'s 导致它走出古怪。

How do I return a string without the \'s in front of the "'s?

如何在“'s 前面没有\'s 的情况下返回一个字符串?

回答by Oleg

Currently your web method return a Stringtogether with ResponseFormat = WebMessageFormat.Json. It follow to the JSON encoding of the string. Corresponds to www.json.org all double quotes in the string will be escaped using backslash. So you have currently double JSON encoding.

目前您的 web 方法返回 aStringResponseFormat = WebMessageFormat.Json. 它遵循字符串的 JSON 编码。对应于 www.json.org 字符串中的所有双引号都将使用反斜杠进行转义。所以你目前有双 JSON 编码。

The easiest way to return any kind of data is to change the output type of GetCurrentCart()web method to Streamor Message(from System.ServiceModel.Channels) instead of String.
See http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx, http://msdn.microsoft.com/en-us/library/ms789010.aspxand http://msdn.microsoft.com/en-us/library/cc681221(VS.90).aspxfor code examples.

返回任何类型数据的最简单方法是将GetCurrentCart()web 方法的输出类型更改为Streamor Message(from System.ServiceModel.Channels) 而不是String.
请参阅http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspxhttp://msdn.microsoft.com/en-us/library /ms789010.aspxhttp://msdn.microsoft.com/en-us/library/cc681221(VS.90).aspx代码示例。

Because you don't wrote in your question which version of .NET you use, I suggest you to use an universal and the easiest way:

因为您没有在问题中写下您使用哪个版本的 .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));
}

回答by Ivix4u

I tried the method suggested by Oleg but found that when i used this method for a large amount of data null key word was appended at the end of the JSON string.

我尝试了 Oleg 建议的方法,但发现当我使用这种方法处理大量数据时,在 JSON 字符串的末尾附加了 null 关键字。

Example:for json with lots of data {"JsonExample":"xxxxx"}null

示例:对于有大量数据的 json {"JsonExample":"xxxxx"}null

found a solution to address this problem at : http://wcf.codeplex.com/workitem/67Wrote the following function which will accept a object and return a Pure Json output. So before returning my object in the main method i make a call to the below method.

http://wcf.codeplex.com/workitem/67找到了解决此问题的解决方案 编写了以下函数,该函数将接受一个对象并返回一个纯 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;
    }

回答by Ahmed Samir

That was great (OlegResponse) and all make sure that you add the line WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";

太好了(OlegResponse),并且确保您添加了 WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8"; 行。

if you removed it result will be downloaded as file .

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

回答by John_J

I recommend to use Jillibrary to Serialize your JSON object or dynamic(ExpandoObject).

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

In my case, It will avoid some null value problem, like always get "{}" from JsonConvert.SerializeXXXand extend {aa:bb} to {key:aa, value:bb} from JavaScriptSerializer

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

full sample here as below.

完整示例如下。

Interface:

界面:

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "json/GetCurrentCart")]
Stream GetCurrentCart(MyRequestParam Param);

Implementation:

执行:

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));
}