合并2个JSON文件Newtonsoft



我有两个json文件,或者String,我想根据ID合并它们。这是一个例子:

我是Json 1:

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

这个i 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
    }]
}

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

{
    "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吗?或者其他方式?但我喜欢牛顿软。

您可以使用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"]]);
}

小提琴原型。

要从文件加载JSON,然后稍后保存,请参阅从文件读取JSON和将JSON写入文件。

相关内容

  • 没有找到相关文章

最新更新