c# – Generate JSON array object from a list type Object

Question:

I am first generating a dynamic object with: dynamic objetoTabla = new ExpandoObject(); , which I add the properties dynamically according to the data that I generate with LINQ , so far everything is fine, then that created object is stored in an Object type list. At the end I do a conversion:

var data = Newtonsoft.Json.JsonConvert.SerializeObject(Lista);

… and return:

return new JsonResult { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

All that returns me the following string:

"[{\" Status \ ": \" 1.1 IN SERVICE \ ", \" BALESIA \ ": 22, \" Total \ ": 160, \" CT \ ": 81, \" TA \ ": 23, \ "TORRESEC \": 27, \ "TU \": 7}, {\ "Status \": \ "2.1 IN INSTALLATION \", \ "BALESIA \": 2, \ "Total \": 22, \ "CT \ ": 11, \" TA \ ": 8, \" TORRESEC \ ": 1, \" TU \ ": 0}]"

Which is wrong, since it puts the quotes at the beginning of the array and the backslashes inside the objects. What am I doing wrong? Is the object type converted to JSON in another way?

I need a JSON array, because that is what my angular table needs. I use dynamic because my angular table is dynamic, and it is assembled according to the properties of the JSON.

I am working in MVC4, C #.

Answer:

I understand that what you are doing is fine. It is returning a JSON contained in a string , the backslashes that you see are to escape the quotation marks, the only thing you need to do, when you receive it from the client side, is:

var jsonString = "[{\"Estado\":\"1.1 EN SERVICIO\",\"BALESIA\":22,\"Total\":160,\"CT\":81,\"TA\":23,\"TORRESEC\":27,\"TU\":7},{\"Estado\":\"2.1 EN INSTALACION\",\"BALESIA\":2,\"Total\":22,\"CT\":11,\"TA\":8,\"TORRESEC\":1,\"TU\":0}]";
JSON.parse(jsonString);

If you try this on the console, you will see that it converts without problems.

Likewise, if what you want is that the property names (Balesia, CT, State, etc.) not appear enclosed in quotes, you can try the following solution:

https://stackoverflow.com/questions/7967885/how-to-convert-object-to-json-with-jsonconvert-without-key-qoutations

Scroll to Top