我在 C#/aspx 中创建了这个 JSON 数组:
[
{
nome: "test",
apelido: "test"
}
]
我想像这样创建 JSON:
{
success: 1,
error: 0,
gestor: "test",
cliente: [
{
nome: "test",
apelido: "test"
}
]
}
这是我的代码:
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);
最佳答案
我只想为此创建一个类(实际上是 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; }
}
现在您可以循环填充这些对象的列表:
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";
现在要序列化它,您可以这样做:
context.Response.Write(JsonConvert.SerializeObject(myObj));
如果您对这个类没有其他用途并且它不太复杂,Charles 对匿名类的建议也非常好。
关于c# - 创建一个json格式的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22995214/