Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net json serializer adding backslash "\" to my properties

Tags:

json

c#

asp.net

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 comes out looking 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.

like image 869
frenchie Avatar asked Sep 06 '11 22:09

frenchie


1 Answers

That should be correct. When sending JSON back to the browser, all property names must be in quotes. The backslashes you see are Visual Studio escaping the strings when viewing them (I hope, you didn't mention when you're seeing this).

If you actually send that data back out on the wire it should come across as

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

which is proper JSON notation.

See Wikipedia for an example of JSON notation.

like image 152
Joshua Avatar answered Nov 20 '22 03:11

Joshua