gpt4 book ai didi

c# - 合并 2 个 JSON 文件 Newtonsoft

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:43 25 4
gpt4 key购买 nike

我有 2 个 json 文件或字符串,我想根据 ID 合并它们。就像加入 sql 一样。这是示例:

这是 Json 1:

{
"City": [{
"CityId": 9,
"CityName": "Kukes"
}, {
"CityId": 18,
"CityName": "Tirana"
}, {
"CityId": 19,
"CityName": "Vlore"
}, {
"CityId": 22,
"CityName": "temp"
}]
}

这是我的 json 2:

{
"Citizen": [{
"CitizenId": 38,
"CitizenLastName": "Bale",
"CitizenName": "Christian",
"City_Id": 19
}, {
"CitizenId": 39,
"CitizenLastName": "ttrtrt",
"CitizenName": "test",
"City_Id": 18
}, {
"CitizenId": 42,
"CitizenLastName": "Freeman",
"CitizenName": "Morgan",
"City_Id": 9
}, {
"CitizenId": 43,
"CitizenLastName": "Snow",
"CitizenName": "Jon",
"City_Id": 9
}, {
"CitizenId": 44,
"CitizenLastName": "test2",
"CitizenName": "test",
"City_Id": 9
}]
}

我希望它合并到一个基于 id 的 json 文件或字符串中,如下所示:

{
"City":
[
{
"CityId":9,
"CityName":"Kukes",
"Citizens" : [{"CitizenId":42,"CitizenLastName":"Freeman","CitizenName":"Morgan","City_Id":9},{"CitizenId":43,"CitizenLastName":"Snow","CitizenName":"Jon","City_Id":9},{"CitizenId":44,"CitizenLastName":"test2","CitizenName":"test","City_Id":9}]
},
{
"CityId":18,
"CityName":"Tirana",
"Citizens" : [{"CitizenId":39,"CitizenLastName":"ttrtrt","CitizenName":"test","City_Id":18}]
},
{
"CityId":19,
"CityName":"Vlore",
"Citizens" : [{"CitizenId":38,"CitizenLastName":"Bale","CitizenName":"Christian","City_Id":19}]
},
{
"CityId":22,
"CityName":"temp",
"Citizens" : []
}
]
}

我试了一整天,还是一无所获。你知道如何用 Newtonsoft 做到这一点吗?还是有其他办法?但我希望使用 newtonsoft。

最佳答案

您可以使用 LINQ to JSON 执行此操作, 使用 ToLookup()查找给定城市的所有公民:

var cities = JToken.Parse(cityJson);
var citizens = JToken.Parse(citizenJson);

var lookup = citizens.SelectTokens("Citizen[*]").ToLookup(c => (string)c["City_Id"]);

foreach (var city in cities.SelectTokens("City[*]"))
{
city["Citizens"] = new JArray(lookup[(string)city["CityId"]]);
}

原型(prototype) fiddle .

要从文件加载 JSON,然后再保存回来,请参阅 Read JSON from a fileWrite JSON to a file .

关于c# - 合并 2 个 JSON 文件 Newtonsoft,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36651961/

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