34

我有一个 C# 列表,如下所示:

var reqUsers = from user in users
    select new
    {
        username = user.username,
        firstName = user.firstName,
        lastName = user.lastName,
        email = user.email
    };

我使用以下内容将/序列化为 JSON( Newtonsoft.JSON ):

var json = JsonConvert.SerializeObject(reqUsers);

使用上面的代码,我得到一个像这样的 json 字符串:

[{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan@test.com" },
 { username: "allison", firstName: "Allison", lastName: "House", email: "al@test.com" },
 { username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan@test.com" } ]

但是这是我需要得到的:因为我使用的是车把模板-

var testdata = {
  users: [
  { username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan@test.com" },
  { username: "allison", firstName: "Allison", lastName: "House", email: "al@test.com" },
  { username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan@test.com" } ]

如何使用 Serializer 来命名 JSON 数组,如上?

4

2 回答 2

78

采用:

var json = JsonConvert.SerializeObject(new { users = reqUsers });
于 2013-04-05T21:02:12.560 回答
1

采用:

var json= new JavaScriptSerializer().Serialize(reqUsers);
于 2014-03-05T07:39:22.740 回答