C#字典键拆分为JSON键值?

时间:2017-02-26 04:14:56

标签: c# json

在C#中我有一个字典:

Dictionary<string,string> dict=new Dictionary<string,string>();
dict.Add("User.Info","Your info");
dict.Add("User.Profile","Profile");
dict.Add("Menu.System.Task","Tasks");
var output=dict???
return Json(output);

我想改变一下:

"User": { "Info": "Your info", "Profile": "Profile" }, "Menu": { "System": { "Task": "Tasks" } } }

按点拆分键,然后转换为嵌套键值对, 因为我正在为angular2做语言资源文件,有没有办法实现这个目标?谢谢

4 个答案:

答案 0 :(得分:2)

使用递归函数可以执行此操作,支持任意数量的“关键级别”(任意数量的点)

功能:

private static void SetValues(string[] keys, int keyIndex, string value, IDictionary<string, object> parentDic)
{
    var key = keys[keyIndex];

    if (keys.Length > keyIndex + 1)
    {
        object childObj;
        IDictionary<string, object> childDict;
        if (parentDic.TryGetValue(key, out childObj))
        {
            childDict = (IDictionary<string, object>)childObj;
        }
        else
        {
            childDict = new Dictionary<string, object>();
            parentDic[key] = childDict;
        }

        SetValues(keys, keyIndex + 1, value, childDict);

    }
    else
    {
        parentDic[key] = value;
    }
}

示例:

 Dictionary<string, string> dict = new Dictionary<string, string>();
 dict.Add("User.Info", "Your info");
 dict.Add("User.Profile", "Profile");
 dict.Add("Menu.System.Task", "Tasks");
 dict.Add("Menu.System.Configuration.Number", "1");
 dict.Add("Menu.System.Configuration.Letter", "A");

 var outputDic = new Dictionary<string, object>();

 foreach (var kvp in dict)
 {
     var keys = kvp.Key.Split('.');
     SetValues(keys, 0, kvp.Value, outputDic);
  }

  var json = JsonConvert.SerializeObject(outputDic);

输出:

{
  "User": {
    "Info": "Your info",
    "Profile": "Profile"
  },
  "Menu": {
     "System": {
       "Task": "Tasks",
       "Configuration": {
          "Number": "1",
          "Letter": "A"
       }
     }
  }
}

答案 1 :(得分:2)

您可以通过覆盖JsonConverter中的WriteJson方法来实现。

class CustomJsonConverter : JsonConverter
    {

        public override bool CanConvert(Type objectType)
        {
            bool result = typeof(Dictionary<string,string>).IsAssignableFrom(objectType);
            return result;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            JObject jo = new JObject();

            foreach (var item in (Dictionary<string,string>)value)
            {
                if (item.Key.Contains("."))
                {
                    if (jo.Property(item.Key.Split('.')[0].ToString()) == null)
                    {
                        jo.Add(item.Key.Split('.')[0],
                               new JObject() { { item.Key.Split('.')[1], item.Value } });
                    }
                    else
                    {
                        var result = jo.Property(item.Key.Split('.')[0].ToString()).Value as JObject; ;
                        result.Add(item.Key.Split('.')[1], item.Value);
                    }
                }
                else
                {
                    jo.Add(item.Key, item.Value);
                }
            }
            jo.WriteTo(writer);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }

示例:

 Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("User.Info", "Your info");
    dict.Add("User.Profile", "Profile");
    dict.Add("Menu.System.Task", "Tasks");

    JsonSerializerSettings obj = new JsonSerializerSettings();
    obj.Converters.Add(new CustomJsonConverter());

    var output1 = JsonConvert.SerializeObject(dict,obj);

输出:

{"User":{"Info":"Your info","Profile":"Profile"},"Menu":{"System":"Tasks"}}

答案 2 :(得分:0)

以下是使用多个级别的一种方法:

        Dictionary<string, object> dict = new Dictionary<string, object>();

        var user = new Dictionary<string, string>();
        user.Add("Info", "Your info");
        user.Add("Profile", "Profile");

        var menu = new Dictionary<string, object>();

        var system = new Dictionary<string, string>();
        system.Add("Task", "Tasks");

        menu.Add("System", system);

        dict.Add("User", user);
        dict.Add("Menu", menu);

        string output = JsonConvert.SerializeObject(dict);

        Console.WriteLine(output);

输出:

  

{&#34;用户&#34; {&#34;信息&#34;:&#34;你的   信息&#34;&#34;简介&#34;:&#34;简介&#34;}&#34;菜单&#34; {&#34;系统&#34; {&#34;任务&# 34;:&#34;任务&#34;}}}

p / s:您需要添加引用Newtonsoft.Json才能运行此示例。参考链接:Serializing and Deserializing JSON

希望这有帮助!

答案 3 :(得分:0)

也许你可以看一下&#34; System.Dynamic.ExpandoObject&#34;