gpt4 book ai didi

json - 使用 JSON.Net 的 C# 到 JSON 序列化

转载 作者:IT老高 更新时间:2023-10-28 12:49:21 25 4
gpt4 key购买 nike

我有一个如下所示的 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" } ]

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

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数组?

最佳答案

用途:

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

关于json - 使用 JSON.Net 的 C# 到 JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15843446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com