Quentin Quentin - 7 months ago 27
JSON Question

Invalid output produced using JSON serialization

I'm trying to convert a .NET object into a JSON string, because I want to be able to read the content of this object in the client side.

Here is my controller code:

public ActionResult Index()
IRightsManager rightsInfo = new RightsManager();

string userId = "ynz362897";

string json = JsonConvert.SerializeObject(rightsInfo.GetSectorsForUser(userId));

Session["test"] = json;

return View();

GetSectorsForUser returns an object which have only one attributes, a list of of another object. Here is the model:

public class Sector
public string Code { get; set; }
public string Name { get; set; }

public Sector(string code, string name)
this.Code = code;
this.Name = name;

public class RightsList
public IList<Sector> Sectors;

public RightsList(IList<Sector> sectors)
this.Sectors = sectors;

Here is GetSectorsForUser code:

public RightsList GetSectorsForUser(string userId)
IRightsManagerDB rightsManager = new RightsManagerDB();

RightsList rightsList = new RightsList(rightsManager.GetSectorsForUser(userId));


The result currently produced by my code is:


Which is unreadable with a for in jQuery client side. I am stuck on this for hours, and I cant find any solutions.

Here is the client code:

var sectors = @Session["Sectors"];

$.each(sectors, function (i, item) {
$('#comboSector').append($('<option>', {
text: item.Name,
value : item.Code


If you're sending the object through AJAX...

ASP.NET MVC handles JSON serialization for you. This means that you don't need the:

string json = JsonConvert.SerializeObject(rightsInfo.GetSectorsForUser(userId));

line. What happens is that you serialize the object yourself, and then ASP.NET MVC serializes it one more time, leading to the actual result, that is a string serialized as JSON. In other words:

  • The first serialization leads to {"Sectors": ...,
  • The serialization of the previous string leads to "{\"Sectors\": ....

If you're embedding the object in JavaScript within HTML...

It seems like this is what you are actually doing, and:

var sectors =  @Session["Sectors"];

is a Razor file. This is a very weird approach (mixing languages, dynamically generating JavaScript, accessing the session from your view¹), but, well, let's assume you know what you are doing.

What happens here is that sectors variable points to a string which contains the JSON-serialized object, not the object itself. If you need to get the object, do:

var sectorsObj = JSON.parse(sectors);
$.each(sectorsObj, ...

JSON.parse decodes a JSON-serialized object. Similarly, JSON.stringify converts an object to its JSON representation.

¹ Accessing the session from your view like you do is not only an abuse of the MVC model and refactoring-unfriendly, but also technically wrong. Limit the view to the contents of the model, and eventually the view bag, when relevant. Avoid using global variables, session, request/response object, etc.