将Dictionary转换为多级JSON

时间:2018-03-09 09:09:39

标签: c# json dictionary

今天我正在尝试将Dictionary<string, string>转换为多级JSON对象/字符串。 Dictionary包含名称空间等密钥。

class可以如下:

public static class SettingsConverter
{
    public static string Convert()
    {
        Dictionary<string, string> settings = new Dictionary<string, string>
        {
            { "settings.common.enabled", "true" },
            { "settings.common.welcome", "Welcome {0}" },
            { "settings.ui.style", "dark" },
            { "properties.help", "www.google.com" },
            { "properties.user.firstname", "John" },
            { "properties.user.lastname", "Doe" }
        };

        string json = JsonConvert.SerializeObject(settings, Formatting.Indented);

        return json;
    }
}

我想要的结果应该是:

{
    "settings":{
        "common":{
            "enabled":"true",
            "welcome":"Welcome {0}"
        },
        "ui":{
            "style":"dark"
        }
    },
    "properties":{
        "help": "www.google.com",
        "user":{
            "firstname":"John",
            "lastname":"Doe"
        }
    }
}

如何才能执行此操作,我是否需要自定义JsonConverter

1 个答案:

答案 0 :(得分:-1)

而不是&lt; string,string&gt;的平面字典,而是创建一个多级字典......

var settings = new Dictionary<string, object>()
            {
                {
                    "settings", new Dictionary<string, object>()
                    {
                        {
                            "common", new Dictionary<string, object>()
                            {
                                {"enabled", "false"},
                                {"welcome", "Welcome {0}"}
                            }
                        }
                    }
                }
            };

这应该序列化您的要求。