使用JSON.Net从C#到JSON序列化

使用JSON.Net从C#到JSON序列化

问题描述:

我有一个C#列表,看起来像这样:

I have a C# List which looks like this:

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

我使用以下代码将JSON转换/序列化为(Newtonsoft.JSON):

I use the below to convert / serialize to JSON ( Newtonsoft.JSON ):

var json = JsonConvert.SerializeObject(reqUsers);

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

With the above code I get a json string like this:

[{ 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" } ]

但是这里是我需要得到的:因为我正在使用把手模板-

however here is what I need to get : since I am using handlebars templating -

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" } ]

如何使用序列化器如上所述命名JSON数组?

How can use the Serializer to name the JSON array as above ?

使用:

var json = JsonConvert.SerializeObject(new { users = reqUsers });