我有一个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" } ]
如何使用序列化器如上所述命名JSON数组?
用:
var json = JsonConvert.SerializeObject(new { users = reqUsers });