我正在尝试将字符串传递给 json 对象,并且它有效。但是json中有一些反斜杠和双引号!我怎样才能删除它们?
我正在使用 c# Web API
。这是我的代码。
public string jsonvalues()
{
var x = new
{
status = "Success"
};
var javaScriptSerializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
var jsonString = javaScriptSerializer.Serialize(x);
return jsonString;
}
当我在 Controller 中返回这个函数时,我得到这样的结果
"{\"status\":\"Success\"}"
最佳答案
发生这种情况是因为您手动(在代码中)将数据序列化为 JSON,当您从 Controller 返回数据时,框架再次序列化相同的东西,它已经是一个 json 格式的字符串!
要解决这个问题,只需不要序列化它,让MVC/Web API
框架完成它的工作并创建一个JSON
你的对象。
如果您正在使用 Web API
,请像这样使用
[HttpGet]
public object jsonvalues()
{
var x = new
{
status = "Success"
};
return x;
}
如果你正在使用MVC
,像这样使用
[HttpGet]
public ActionResult jsonvalues()
{
var x = new
{
status = "Success"
};
return Json(x, JsonRequestBehavior.AllowGet);
}
两者都会返回
{ status: "Success" }
关于c# - 如何删除json字符串中的反斜杠和双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33101519/