Question

I have this JSON array created in C#/aspx:

[
 {
 nome: "test",
 apelido: "test"
 }
]

And I want to create JSON like this:

{
  success: 1, 
  error: 0, 
  gestor: "test", 
  cliente: [
    {
      nome: "test",
      apelido: "test"
    } 
  ]
}

this is the code that i have:

var gestor = new JArray();
foreach (System.Data.DataRow item in com.Execute("select * from utilizadores").Rows)
{
    gestor.Add(new JObject(new JProperty("nome", item["first_name"].ToString()),
               new JProperty("apelido", item["last_name"].ToString())));
}
context.Response.Write(gestor);
Was it helpful?

Solution 2

The most succinct way to do this is just with an anonymous class, if you are throwing this to some client side code and not really messing around with this exact object again elsewhere in server side code this is the easiest way to handle it.

var outputString = JsonConvert.SerializeObject(new { 
        success=1, 
        error=0, 
        gestor="test", 
        cliente = (from System.Data.DataRow i in com.Execute("select * from utilizadores").Rows 
                  select new { 
                     nome=item["first_name"],
                     apelido= item["last_name"] 
        }).ToArray()
});

OTHER TIPS

I would just create a class for this (actually 2):

public class MyClass
{
    public int success { get; set; }
    public int error { get; set; }
    public string gestor { get; set; }
    public List<Cliente> cliente { get; set; }
}

public class Cliente
{
    public string nome { get; set; }
    public string apelido { get; set; }
}

And now you can loop to populate a list of these objects:

var myObj = new MyClass();
myObj.cliente = new List<Cliente>();

foreach (System.Data.DataRow item in com.Execute("select * from utilizadores").Rows)
{
     myObj.cliente.Add(new Cliente() 
     {
         nome = item["first_name"].ToString(),
         apelido = item["last_name"].ToString()
     };
}

// assuming that is successful
myObj.success = 1;
// not sure how you wanted this to be populated:
myObj.gestor = "test";

And now to serialize it you can just do:

context.Response.Write(JsonConvert.SerializeObject(myObj));

Charles' suggestion of anonymous classes is also perfectly fine if you have no other use for this class and it's not too complicated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top