gpt4 book ai didi

c# - 带有键名的json字典

转载 作者:行者123 更新时间:2023-11-30 21:43:13 28 4
gpt4 key购买 nike

我有一本字典Dictionary<int, string>整数和字符串,其中整数是 ID,字符串是用户名,当我将其转换为 JSON 时使用 Json.NET我得到如下内容:

{"3":"jack","2":"john"}

我是这样转换的:

Dictionary<int, string> dictFriends = new Dictionary<int, string>();

foreach (var id in resultList)
{
var user = db.Users.Find(id);
string friend = user.Username;

dictFriends.Add(id, friend);
}

string json = JsonConvert.SerializeObject(dictFriends);

但我希望得到这样的东西:

[
{ "id": "3", "user": "jack"},
{ "id": "2", "user": "john"},
]

这可能吗?

最佳答案

据我所知,您必须将字典转换为 JSON.NET 会识别为 IEnumerable 的内容:

// YOUR DICTIONARY
var dictFriends = new Dictionary<int, string>() {
{1,"Jack"},
{2,"John"},
{3,"Jeff"}
};

// TRANSFORM INTO IENUMERABLE
var transformed = from key in dictFriends.Keys
select new { id = key, user = dictFriends[key] };

// SERIALIZE
var json = JsonConvert.SerializeObject(transformed);

输出:

[
{"id":1, "user":"Jack"},
{"id":2, "user":"John"},
{"id":3, "user":"Jeff"}
]

关于c# - 带有键名的json字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41891139/

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