Asp.net json serializer adds backslash "\" to my properties

I have an object model that looks like this:

public class MyObjectModel { public int1 {get;set;} public int2 {get;set;} [ScriptIgnore] public int3 {get;set;} } 

In my code, I write this:

 MyObjectModel TheObject = new MyObjectModel(); TheObject = LoadFromQuery(); //populates the properties using a linq-to-sql query JavaScriptSerializer MyObjectSerializer = new JavaScriptSerializer(); string TheObjectInJson = MyObjectSerializer.Serialize(TheObject); 

When I look at the json string TheObjectInJson, it looks like this:

 "{\"int1\":31,\"int2\":5436}" 

The serializer adds a backslash to each property. I tried adding and removing the [Serializable] attribute above the class definition, but to no avail.

Any suggestions why this is happening?

Thanks.

+6
source share
2 answers

That should be right. When sending JSON back to the browser, all property names must be in quotation marks. The backslashes you see are Visual Studio, avoiding lines when viewing them (I hope you didn't mention it when you see this).

If you really send this data on a wire, they should occur as

 {"int1": 31, "int2":5436} 

which is the proper JSON designation.

See Wikipedia for an example of JSON notation.

+10
source

In your controller, return the type of your object (not as a string!) As a JsonResult, i.e.:

 [HttpGet] public JsonResult<MyObjectModel> GetMyObject() { var theObject = LoadFromQuery(); //populates the properties (however) return Json(theObject); } 
0
source

Source: https://habr.com/ru/post/896749/


All Articles