简体   繁体   中英

double quot in string via JSON and asp.net mvc

return string in json format via webform , " will be escaped correctly and all works good , but in mvc " will be show in \\" format , so josn format will be corrupted

this code is in mvc that return "name\\":\\"MSLM"

public ActionResult Index()
{
   string s = @"name"":""MSLM";
   return Json(s, JsonRequestBehavior.AllowGet);
}

this code is in webform works correctly and return "name":"MSLM"

Response.Clear();
Response.Charset = "utf8";
Response.ContentType = "application/json";
string s = @"name"":""MSLM";
Response.Write(s);
Response.End();

string tested via serialization via this code but not works too

JavaScriptSerializer js = new JavaScriptSerializer();
string s = "\"asdfasdf\":\"asdfad\"";
return js.Serialize(s);

Your first example, where you say the output is correct, is not correct.

string s = @"name"":""MSLM";

This translates to the string name":"MSLM

Note that I did not use quotes to delimit the string. Just like the string foo can be typed as "foo", name":"MSLM can be noted as "name":"MSLM".

Your second example, however, seemd to be exactly what you want.

string s = "\"asdfasdf\":\"asdfad\"";

This translates to the string "asdfasdf":"asdfad" . Which can be written as ""asdfasdf":"asdfad"". Look at the double quotes at the start and end . The outer set of quotes denote where your string s stops. The inner set of quotes are used to wrap around the asdfasdf values.

The second example could also be phrased as the following:

string s = @"""asdfasdf"":""asdfad""";

These two snippets are equivalent. Using the @"mystring" notation is usually used for scenarios where you want to enter multi-line string variables, but can be used on a single line as well (I don't see why you'd use it, but it is valid).

Long story short, example 2 is correct, example 1 isn't. I suspect you've made an error during testing, hence the confusion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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