如何删除JSON字符串反斜线和双引号 [英] how to remove backslashes and double quotes in json string
问题描述
我试图传递字符串JSON对象,和它的作品。但也有一些反斜线和双引号中的JSON!如何删除它们?
我使用C#的Web API
。这是我的code。
公共字符串jsonvalues()
{
变种x =新
{
状态=成功
};
VAR的JavaScriptSerializer =新
System.Web.Script.Serialization.JavaScriptSerializer();
VAR jsonString = javaScriptSerializer.Serialize(X);
返回jsonString;
}
当我返回控制这个功能,我得到这样的结果。
{\\状态\\:\\成功\\}
块引用>解决方案这是发生,因为你是手动序列化数据,以JSON(在code)和当您从控制器返回数据,该框架序列化一样再一点,这已经是一个JSON格式的字符串!
要解决这个问题,根本的不序列化,让
MVC /网络API
框架完成其工作,并创建一个JSON
你的对象。如果您使用的是
的Web API
使用这样[HTTPGET]
公共对象jsonvalues()
{
变种x =新
{
状态=成功
};
返回X;
}如果您使用的是
MVC
,这样使用[HTTPGET]
公众的ActionResult jsonvalues()
{
变种x =新
{
状态=成功
};
返回JSON(X,JsonRequestBehavior.AllowGet);
}双方将返回
{状态:成功}
块引用>I am trying to pass string to json object, and it works. However there are some backslashes and double quotes in the json! How can I remove them?
I am using 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!
To solve that, simply do not serialize it, let the
MVC/Web API
framework do its job and create aJSON
out of your object.If you are using
Web API
use like this[HttpGet] public object jsonvalues() { var x = new { status = "Success" }; return x; }
If you are using
MVC
, use like this[HttpGet] public ActionResult jsonvalues() { var x = new { status = "Success" }; return Json(x, JsonRequestBehavior.AllowGet); }
Both will return
{ status: "Success" }
这篇关于如何删除JSON字符串反斜线和双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!