如何从C#生成最佳的JSON?

4
我正在尝试模仿一个使用硬编码JSON的示例。
{
"page": 1,
"total": 1,
"records": 2,
"rows": [
   {"id": 1, "cell": ["1", "Super Item", "300", 0, null, false, false]},
       {"id": 2, "cell": ["2", "Item 1", "100", 1, 1, false, false]},
       {"id": 3, "cell": ["3", "Sub Item 1", "50", 2, 2, true, true]},
       {"id": 4, "cell": ["4", "Sub Item 2", "25", 2, 2, false, false]},
       {"id": 5, "cell": ["5", "Sub-sub Item 1", "25", 3, 4, true, true]},
       {"id": 6, "cell": ["6", "Sub Item 3", "25", 2, 2, true, true]},
       {"id": 7, "cell": ["7", "Item 2", "200", 1, 1, false, false]},
       {"id": 8, "cell": ["8", "Sub Item 1", "100", 2, 7, false, false]},
       {"id": 9, "cell": ["9", "Sub-sub Item 1", "50", 3, 8, true, true]},
       {"id": 10, "cell": ["10", "Sub-sub Item 2", "50", 3, 8, true, true]},
       {"id": 11, "cell": ["11", "Sub Item 2", "100", 2, 7, true, true]}
    ]
} 

但是我需要从C#生成它。有没有关于在C#中生成上述内容的最佳建议?


请查看Json.NET - Kirill Polishchuk
2
DataContractJsonSerializer(内置)或Json.net - CodesInChaos
看起来答案取决于更多信息。例如,你使用 ASP.NET MVC、WCF 还是 ASMX Web 服务?你使用哪个 .NET 版本? - Oleg
@Oleg - 这是关于MVC的,因为我正在尝试玩jqgrid Treegrid。您有任何树形网格和asp.net-mvc的示例吗(鉴于您是专家:))? - leora
我主要使用本地数据的树形表格。在远程数据的情况下,您应该只生成具有附加隐藏列值的数据。请参见答案这里。重要的是要理解“loaded”列的含义,并且要了解jqGrid树形表格不支持分页。 - Oleg
4个回答

11

Controller类有一个Json方法,可以将对象序列化为JSON格式,因此在您的操作方法中,只需创建对象并调用该方法:

public ActionResult GetData() {
  return Json(
    new {
      page = 1,
      total = 1,
      records = 2,
      rows = new[] {
        new { id = 1, cell = new object[] { "1", "Super Item", "300", 0, null, false, false } },
        new { id = 2, cell = new object[] { "2", "Item 1", "100", 1, 1, false, false } },
        new { id = 3, cell = new object[] { "3", "Sub Item 1", "50", 2, 2, true, true } },
        new { id = 4, cell = new object[] { "4", "Sub Item 2", "25", 2, 2, false, false } },
        new { id = 5, cell = new object[] { "5", "Sub-sub Item 1", "25", 3, 4, true, true } },
        new { id = 6, cell = new object[] { "6", "Sub Item 3", "25", 2, 2, true, true } },
        new { id = 7, cell = new object[] { "7", "Item 2", "200", 1, 1, false, false } },
        new { id = 8, cell = new object[] { "8", "Sub Item 1", "100", 2, 7, false, false } },
        new { id = 9, cell = new object[] { "9", "Sub-sub Item 1", "50", 3, 8, true, true } },
        new { id = 10, cell = new object[] { "10", "Sub-sub Item 2", "50", 3, 8, true, true } },
        new { id = 11, cell = new object[] { "11", "Sub Item 2", "100", 2, 7, true, true } }
      }
    } 
  );
}

如果创建可序列化类太过麻烦,那么这对于一次性的事情非常有用。同时,它也是最接近 JS 等效的方法。 - Davy8

4

在.Net 2+中有一个名为“JavaScriptSerializer”的类,它可以基于.Net类型的类创建一个JSON结构化字符串。

使用该序列化程序,您可以简单地创建具有属性和集合的类来表示您的JSON数据。在.Net服务器端代码中创建一个实例,然后使用序列化程序响应以生成有效的JSON字符串响应。

以下是将Person类实例转换为序列化JSON字符串的示例:

JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = "Brian";
p1.lastName = "Scott";
p1.department = "Microsoft";
p1.address.addressline1 = "Microsoft";
p1.address.addressline2 = "";
p1.address.city = "Redmond";
p1.address.state = "Seattle";
p1.address.country = "America";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };

string strJSON = js.Serialize(p1);

这将生成一个有效的JSON字符串。
{"firstName":"Brian","lastName":"Scott","department":"Microsoft","address":{"addressline1":"Microsoft","addressline2":"","city":"Redmond","state":"Seattle","country":"America","pin":560028},"technologies":["IIS","ASP.NET","JavaScript","AJAX"]}

如果你打算使用webservice来生成向客户端发送的JSON响应,那么你可以将你的方法标记为:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetPersonJSON()
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    Person p1 = new Person();
p1.firstName = "Brian";
p1.lastName = "Scott";
p1.department = "Microsoft";
p1.address.addressline1 = "Microsoft";
p1.address.addressline2 = "";
p1.address.city = "Redmond";
p1.address.state = "Seattle";
p1.address.country = "America";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };

return js.Serialize(p1);
}

1
似乎需要3.5+版本。但仍然不需要任何外部插件。 - cHao
1
谢谢,我以为这是2.0+的包含,但现在我想起来这个类是随着其他3.0的System.web.extension类一起出现的。干杯。 - Brian Scott

1

看起来您正在尝试填充jqGrid,并且正在使用ASP.NET MVC。 如果您为这些值定义了一个类:

["1", "Super Item", "300", 0, null, false, false]

您可以将所有元素存储在集合myCollection
您可以这样做:

var ReturnData = new
    {
        total = totalPages,
        page = page,
        records = totalRecords,
        rows = myCollection.Select(r => new
        {
            id = r.Id.ToString(),
            cell = new String[] { r.Field1, r.Field2, r.Field3, r.Field4 }
        })
        };

return (Json(ReturnData, JsonRequestBehavior.DenyGet));

0
class Row {
   public int id {get;set;}
   public object[] cell {get;set;}
}

class Data {
  public int page {get;set;}
  public int total {get;set;}
  public int records {get;set;}
  public Row[] rows {get;set;}
}

var myData = new Data(){ .... };
var json =  new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(myData);

这些类不可序列化。 - harryovers
它们不需要可序列化。因为它没有使用二进制序列化或JSON数据契约,而是使用不涉及Serializable属性的Json序列化。 - rpgmaker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接