c# - 创建一个json格式的对象

标签 c# asp.net json httphandler

我在 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/

相关文章:

json - 如果连接不匹配,如何与 json_build_object 一起返回 null?

c# - WebClient 生成 (401) 未经授权的错误

asp.net - asp.net 3.5 是否支持单个页面上的多个表单?

c# - linq to entities left outer join

c# - 如何通过jquery/javascript获取更新后的隐藏字段值代码

c# - .NET 的单元测试框架,比较?

java - 使用 java 迭代 JSON 响应中存在的最后一个值

arrays - Swift:遍历字典数组

c# - 将数据绑定(bind)到 ListView ItemDataBound 内的 Gridview 实例

C# 解密值和公共(public)类属性...有什么风险?