2

With JSON.NET I can serialize a generic list into a JSON string:

 return Json(new { success = true, data = JsonConvert.SerializeObject(units) });

but how can I serialize a generic list into JSON objects. This would have the advantage that I do not need this on client side:

var jsonData = $.parseJSON(units);
Elisabeth
  • 20,496
  • 52
  • 200
  • 321

2 Answers2

4

Don't serialize a part of the object, serialize the entire object:

return Content(JsonConvert.SerializeObject(new { success = true, data = units }), "text/javascript");

The built-in Json method is hard-coded to return a result that uses the built-in (somewhat limited) .NET JavaScript serializer. If you want to get something as easy to use as that, add your own "Json" method into your base controller class that does the same thing with Json.NET.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • using your code I get an parsererror. serializing the success = true is not needed at all. The success = true is checked in the response.success in a generic way, I cant change that handling. – Elisabeth May 28 '12 at 10:52
  • Your answer in general is correct. It just did not fit to this special situation I have with the success = true. But I do a lot other getJSON where I do not need this success= true stuff. – Elisabeth May 28 '12 at 12:06
  • @Elisa: An object will have to be serialized in some way for it to be passed over HTTP. Did you understand what I was doing here? If you get a parse error, do go ahead and fix it as I didn't actually try this out. – Matti Virkkunen May 29 '12 at 15:22
1

Check out this link.
I personally use json2.js, and JSON.parse/stringify to cnovert strings to ojbects and vice versa

p.s its stil done on the client side, but its just another line of code to add

Community
  • 1
  • 1
YavgenyP
  • 2,113
  • 14
  • 11
  • Why not just: JSON.parse(jsonString); its not supported in all browsers, jquery.parseJSON(jsonstring) is the prefered way which I use already and this is said too in the link you referenced ;-) – Elisabeth May 28 '12 at 11:04
  • @Elisa, when i was lookign for a way to do the conversion to both ways, i didnt find anything that worked except for json2.js (couldnt find the orignial SO link, so i used this one). However i remember reading that even the creator of jquery recommends using json2.js – YavgenyP May 28 '12 at 11:07
  • http://stackoverflow.com/questions/3238842/should-jquerys-parsejson-getjson-methods-be-used READ the solution. Its interesting. Your json2.js tip is put on my optimization list for later. – Elisabeth May 28 '12 at 12:04