C# 返回 Json,但它包含反斜杠“\”,这是我不想要的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13833900/
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-08-10 09:56:00  来源:igfitidea点击:

Return Json, but it includes backward slashes "\", which i don't want

c#jsonasp.net-mvc-4asp.net-web-api

提问by riseres

I use MVC4 web-api, c#, and want to return Json using Json.net.

我使用 MVC4 web-api、c#,并且想使用 Json.net返回 Json

the problem is it comes with "backward slashes".

问题是它带有“向后斜线”。

I also added this code to Global.asax.

我还将此代码添加到 Global.asax。

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

here is what it returns.

这是它返回的内容。

"{\"cid\":1,\"model\":\"WT50JB\",\"detail\":\"sdf??\",\"unit\":2,\"time_in\":\"2012-12-11T19:00:00\",\"time_out\":\"2012-12-12T13:00:06.2774691+07:00\",\"time_used_dd\":0.0,\"time_used_hh\":0.0}"

so what i want to see is

所以我想看到的是

{"cid":1,"model":"WT50JB","detail":"sdf??","unit":2,"time_in":"2012-12-11T19:00:00","time_out":"2012-12-12T13:08:50.5444555+07:00","time_used_dd":0.0,"time_used_hh":0.0}

here is JsonConvertor

这是 JsonConvertor

string json = JsonConvert.SerializeObject(myObj);

采纳答案by riseres

i found the solution here it is

我在这里找到了解决方案

return new HttpResponseMessage() 
{
    Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};

回答by Codo

Most likely, the slashes are an artifact because you copied them out of the VisualStudio debugger. The debugger displays all strings in a way that they could be pasted into C/C# code. They aren't really in the transmitted data.

最有可能的是,斜线是人工制品,因为您将它们从 VisualStudio 调试器中复制出来。调试器以一种可以将它们粘贴到 C/C# 代码中的方式显示所有字符串。它们并不真正存在于传输的数据中。

BTW: These slashes are backwardslashes. A forward slash would look like this: /.

BTW:这些斜杠是落后的斜线。正斜杠看起来像这样:/。

回答by id.ot

I had the same issue, until just a few moments ago. Turns out that I was "double serializing" the JSON string. I use a jQuery $.getJson(AJAX call to a JsonResultcontroller action. And because the action builds a C# Generic List<t>I thought that I had to use JSON.net/NewtonSoft to convert the C# Generic List<t>to a JSON object before returning the JSON using the following:

我遇到了同样的问题,直到几分钟前。原来我正在“双重序列化”JSON 字符串。我使用 jQuery $.getJson(AJAX 调用JsonResult控制器操作。并且因为该操作构建了一个 C# 泛型,List<t>我认为我必须使用 JSON.net/NewtonSoft 将 C# 泛型List<t>转换为 JSON 对象,然后使用以下内容返回 JSON:

return Json(fake, JsonRequestBehavior.AllowGet);

I didn't have to use the JsonConvert.SerializeObject(method after all, evidently this returnwill conver the serialization for us.

毕竟我不必使用该JsonConvert.SerializeObject(方法,显然这return将为我们转换序列化。

Hope it helps you or someone else too.

希望它也能帮助你或其他人。

回答by Maulik

using Newtonsoft.Json.Linq;
string str = "Your String with Back Slashes";
str = JToken.Parse(str).ToString(); `// Now You will get the Normal String with "NO SLASHES"`

回答by Sam khan

I found the solution and worked for me (Y)

我找到了解决方案并为我工作(Y)

var yourString = yourString.Replace("\","");

I got it from here

我从这里得到的

回答by Sufiyan Ansari

Here i found the solution:

在这里我找到了解决方案:

                    response = response.replace("\"", "\").replace("\\", "\"").replace("\", "");
                JSONArray PackageData = new JSONArray(response);
                SelectSymbolList.clear();
                for (int i = 0; i < PackageData.length(); i++) {
                    JSONObject jsonData = PackageData.getJSONObject(i);
                    // get your array here
                }

回答by Jitendra Bansiwal

I found the solution and its worked for me:

我找到了解决方案,它对我有用:

var json = JsonConvert.SerializeObject(sb.ToString(), Formatting.Indented);
response.Content = new StringContent(json, Encoding.UTF8 , "application/json");

回答by Andrew Birks

For the sake of seeing a "full" snippet of code, this is what I used to achieve a solution:

为了看到“完整”的代码片段,这是我用来实现解决方案的:

    [AllowAnonymous]
    [HttpGet]
    public HttpResponseMessage GetAllMessages()
    {

        try
        {
            //Load Data Into List
            var mm = new MessageManager();
            List<Message> msgs = mm.GetAllMessages();

            //Convert List Into JSON
            var jsonmsgs = JsonConvert.SerializeObject(msgs);

            //Create a HTTP response - Set to OK
            var res = Request.CreateResponse(HttpStatusCode.OK);

            //Set the content of the response to be JSON Format
            res.Content = new StringContent(jsonmsgs, System.Text.Encoding.UTF8, "application/json");

            //Return the Response
            return res;
        }
        catch (Exception exc)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
        }
    }

回答by Alok Mishra

Mostly It occurs due to double serialization. I had same issue a while back where I had to serialize a collection into Json string and even after trying various workarounds I was unable to resolve it. So, at last removed all the serialization code and simply returned the collection object and the serialization was taken care of by default. So try removing the serialization code and simply returning the return type. Hope it helps someone with similar issues.

主要是由于双重序列化而发生的。不久前我遇到了同样的问题,我不得不将一个集合序列化为 Json 字符串,即使在尝试了各种解决方法之后我也无法解决它。所以,最后删除了所有的序列化代码,简单地返回了集合对象,序列化是默认处理的。所以尝试删除序列化代码并简单地返回返回类型。希望它可以帮助有类似问题的人。

回答by Heriberto Lugo

After hours of trying to figure this out, one popular response to this question seemed to be spot on accurate for me. But, not in the manner I imagined.

经过数小时的尝试弄清楚这一点后,对这个问题的一个流行回答对我来说似乎是准确的。但是,不是我想象的那样。

My code was very very simple:

我的代码非常非常简单:

this.Request.CreateResponse(HttpStatusCode.Accepted, new JavaScriptSerializer().Serialize(obj));

I was sure the the popular response of "double serializing" did not apply to me. After all, I was explicitly serializing my object to JSON only once.

我确信“双重连载”的流行反应不适用于我。毕竟,我只将对象显式序列化为 JSON 一次。

I tried this snippet:

我试过这个片段:

new StringContent(json, System.Text.Encoding.UTF8, "application/json")

Which did not even seem to contain my data! Instead this is what i received:

其中甚至似乎不包含我的数据!相反,这是我收到的:

{
  "Headers": [
    {
      "Key": "Content-Type",
      "Value": [
        "application/json; charset=utf-8"
      ]
    }
  ]
}

Hmmm... But lo and behold! Looking closely at my original response in the Swagger UI, and after copy and pasting it into a JSON beautifier - I was in fact somehow "double serializing". Using the following code is what yielded the correct JSON response:

嗯……但是你瞧!仔细查看我在 Swagger UI 中的原始响应,并在将其复制并粘贴到 JSON 美化器中之后 - 实际上我以某种方式进行了“双重序列化”。使用以下代码生成正确的 JSON 响应

 this.Request.CreateResponse(HttpStatusCode.Accepted, obj);

That's right! just send the serializable object directly, no need to serialize to JSON! Seems the response automagically serializes objects into JSON. Hope this helps!

这是正确的!直接发送序列化对象即可,无需序列化为JSON!似乎响应自动将对象序列化为 JSON。希望这可以帮助!

EDIT: If you begin with a JSON string, like let's say from database, you can deserialize the string into an object and return that object - like so:

编辑:如果你从一个 JSON 字符串开始,比如从数据库中说,你可以将字符串反序列化为一个对象并返回该对象 - 像这样:

object obj = new JavaScriptSerializer().DeserializeObject(json);
this.Request.CreateResponse(HttpStatusCode.Accepted, obj);