Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#字典键拆分为JSON键值?_C#_Json - Fatal编程技术网

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

C#字典键拆分为JSON键值?,c#,json,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); 按点拆分键,然后转

在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);
按点拆分键,然后转换为嵌套的键值对,
因为我正在为angular2编写语言资源文件,有什么方法可以归档吗?谢谢这里有一种方法可以使用多个级别:

        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);
Dictionary dict=new Dictionary();
var user=newdictionary();
添加(“信息”、“您的信息”);
添加(“配置文件”、“配置文件”);
var菜单=新字典();
var system=newdictionary();
添加(“任务”、“任务”);
菜单。添加(“系统”,系统);
dict.Add(“用户”,用户);
添加(“菜单”,菜单);
字符串输出=JsonConvert.SerializeObject(dict);
控制台写入线(输出);
输出:

{
  "User": {
    "Info": "Your info",
    "Profile": "Profile"
  },
  "Menu": {
     "System": {
       "Task": "Tasks",
       "Configuration": {
          "Number": "1",
          "Letter": "A"
       }
     }
  }
}
{"User":{"Info":"Your info","Profile":"Profile"},"Menu":{"System":"Tasks"}}
{“用户”:{“信息”:“您的 信息,“配置文件”:“配置文件”},“菜单”:{“系统”:{“任务”:“任务”}}

p/s:您需要添加reference
Newtonsoft.Json
来运行此示例。参考链接:


希望这有帮助

这里有一种使用多个级别的方法:

        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);
Dictionary dict=new Dictionary();
var user=newdictionary();
添加(“信息”、“您的信息”);
添加(“配置文件”、“配置文件”);
var菜单=新字典();
var system=newdictionary();
添加(“任务”、“任务”);
菜单。添加(“系统”,系统);
dict.Add(“用户”,用户);
添加(“菜单”,菜单);
字符串输出=JsonConvert.SerializeObject(dict);
控制台写入线(输出);
输出:

{
  "User": {
    "Info": "Your info",
    "Profile": "Profile"
  },
  "Menu": {
     "System": {
       "Task": "Tasks",
       "Configuration": {
          "Number": "1",
          "Letter": "A"
       }
     }
  }
}
{"User":{"Info":"Your info","Profile":"Profile"},"Menu":{"System":"Tasks"}}
{“用户”:{“信息”:“您的 信息,“配置文件”:“配置文件”},“菜单”:{“系统”:{“任务”:“任务”}}

p/s:您需要添加reference
Newtonsoft.Json
来运行此示例。参考链接:


希望这有帮助

也许您可以查看“System.Dynamic.ExpandoObject”

也许您可以查看“System.Dynamic.ExpandoObject”

使用递归函数,您可以做到这一点,支持任意数量的“关键级别”(任意数量的点)

功能:

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;
    }
}

使用递归函数可以做到这一点,支持任意数量的“关键级别”(任意数量的点)

功能:

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;
    }
}

可以通过重写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();
        }
    }

可以通过重写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();
        }
    }

这应该是评论而不是回答。这应该是评论而不是回答。太好了!但最后我发现会有一个问题,就是每个都必须有相同数量的级别,例如dict.Add(“User.Profile”,“Profile”);dict.Add(“User.Profile.Title”,“您的个人资料”);这将发生错误,所以最后我得到了删除所有的点并使用简单的字符串。该结构在给定的示例中不适用?您需要一个属性user.profile,它的值为“profile”,但也需要一个属性use.profile,它有一个值字典,如title和“your profile”?太好了!但最后我发现会有一个问题,就是每个都必须有相同数量的级别,例如dict.Add(“User.Profile”,“Profile”);dict.Add(“User.Profile.Title”,“您的个人资料”);这将发生错误,所以最后我得到了删除所有的点并使用简单的字符串。该结构在给定的示例中不适用?您需要一个值为“profile”的属性user.profile,还需要一个属性use.profile,它有一个值字典,例如title和“your profile”?