首页 > 解决方案 > C# 将 JSON 序列化为简单的字典

问题描述

我有以下json:

{
    "Name" : "Value1",
    "Data": [
        {
            "UserName": "test",
            "email": "test@test.com",
            "UserInformation": {
                "City": "city",
                "country:": "country"
            }
        },        
        {
            "UserName": "test1",
            "email": "test1@test.com"
        }
    ]
}

我想要下一本字典:

{
    "Name" : "Value1",
    "Data[0].UserName": "test",
    "Data[0].email": "test@test.com",
    "Data[0].UserInformation.City": "city",
    "Data[0].UserInformation.country": "country",
    "Data[1].UserName": "test1",
    "Data[1].email": "test1@test.com"
}

使用 Newtonsoft.Json 无助于解决我的问题。拜托,你能帮帮我吗?

标签: c#jsonserialization

解决方案


如果我理解正确,您正在寻找这样的东西(使用 Newtonsoft.Json):

var dictionary = JObject.Parse(json)
    .Descendants()
    .OfType<JValue>()
    .ToDictionary(jv => jv.Path, jv => jv.ToString());

推荐阅读