Generate JSON array object from a list type Object

4

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

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

... and return:

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

All that returns to me the following chain:

  

"[{\" 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 inverted bars 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's what my angular table needs. I use dynamic because my angular table is dynamic, and it is armed according to the JSON properties.

I'm working on MVC4, C #.

    
asked by cristian gonzalez 10.11.2016 в 05:20
source

2 answers

1

I understand that what you are doing is fine. You are returning a JSON contained in a string , the backslashes that you see are to escape the quotes, the only thing you would miss, when you receive it from the side of the client, 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 is converted without problems.

Likewise, if what you want is that the names of the properties (Balesia, CT, State, etc.) enclosed in quotation marks do not appear, you can try the following solution:

link

    
answered by 15.11.2016 в 12:55
0

What you must do is create a class that has the properties that you generate in LINQ, since when converting it to JSON with Newtonsoft; is not able to perform the conversion of the dynamic properties.

Maybe you want to save a few lines of code using dynamic, but you must use it by creating a DTO.

You should have something like that

public class Detalle { 
    public string Estado { get; set; }
    public int BALESIA { get; set; }
    ...
}

List<Detalle> detalles = (from x in ... db...... select new Detalle { ..... }).ToList();
return new JsonResult { Data = detalles, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    
answered by 16.11.2016 в 00:24