简体   繁体   English

如何删除json字符串中的反斜杠和双引号

[英]how to remove backslashes and double quotes in json string

I am trying to pass string to json object, and it works. 我试图将字符串传递给json对象,它的工作原理。 However there are some backslashes and double quotes in the json! 然而,在json中有一些反斜杠和双引号! How can I remove them? 我该如何删除它们?

I am using c# Web API . 我正在使用c# Web API This is my code. 这是我的代码。

public string jsonvalues()
{
    var x = new
    {  
      status = "Success"
    };
    var javaScriptSerializer = new
    System.Web.Script.Serialization.JavaScriptSerializer();
    var jsonString = javaScriptSerializer.Serialize(x);
    return jsonString;
}  

When I return this function in controller, I get the result like this 当我在控制器中返回此函数时,我得到这样的结果

"{\\"status\\":\\"Success\\"}" “{\\” 状态\\ “:\\” 成功\\ “}”

This is happening because you are serializing the data to JSON manually (in code) and when you return the data from controller, the framework serializes the same thing again, which is already a json formatted string! 发生这种情况是因为您手动将数据序列化为JSON(在代码中),当您从控制器返回数据时,框架再次序列化相同的东西,这已经是一个json格式的字符串!

To solve that, simply do not serialize it , let the MVC/Web API framework do its job and create a JSON out of your object. 要解决这个问题,只需不要序列化它 ,让MVC/Web API框架完成它的工作并从你的对象中创建一个JSON

If you are using Web API use like this 如果您正在使用这样的Web API

[HttpGet]
public object jsonvalues()
{
    var x = new
    {
        status = "Success"
    };
    return x;
}

If you are using MVC , use like this 如果您使用的是MVC ,请使用这样的方法

[HttpGet]
public ActionResult jsonvalues()
{
    var x = new
    {
        status = "Success"
    };
    return Json(x, JsonRequestBehavior.AllowGet);
}

Both will return 两者都将回归

{ status: "Success" } {status:“成功”}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM