将json字符串转换为多维数组

时间:2014-07-31 14:26:01

标签: c# arrays json multidimensional-array

这是我目前的jSON数组:

{"1": [{"11": [[1, 1],[2, 2],[3, 3]],"21": [[1, 1],[2, 2],[3, 3]],"31": [[1, 1],[2, 2],[3, 3]]}],"4": [{"12": [[1, 1],[2, 2],[3, 3]],"22": [[1, 1],[2, 2],[3, 3]],"32": [[1, 1],[2, 2],[3, 3]]}],"6": [{"13": [[1, 1],[2, 2],[3, 3]],"23": [[1, 1],[2, 2],[3, 3]],"33": [[1, 1],[2, 2],[3, 3]]}]}

我想将其转换为Dictionary<int, Dictionary<int, Dictionary<int, int>>>

我已经搜索了很长时间但找不到可能的解决方案。到现在为止,我有:

Dictionary<int, Dictionary<int, Dictionary<int, int>>> menus = new Dictionary<int, Dictionary<int, Dictionary<int, int>>>();

        JToken entireJson = JToken.Parse(rawDirectory);

        foreach (var item in entireJson.Children())
        {
            var property = item as JProperty;
            var subArray = new Dictionary<int, Dictionary<int, int>>();
            foreach (var subItem in property.Value.Children())
            {
                var subProperty = subItem as JProperty;
                var subSubArray = new Dictionary<int, int>();
                foreach (var subSubItem in subItem)
                {
                    var subSubProperty = subSubItem as JProperty;
                    subSubArray.Add(int.Parse(subSubProperty.Name), int.Parse((String)subSubProperty.Value));
                }
                subArray.Add(int.Parse(subProperty.Name), subSubArray);
            }
            menus.Add(int.Parse(property.Name), subArray);
        }

修改 - 解决方案

要根据需要生成Dictionary<>,我必须稍微更改jSON数组。当您使用括号[]时,它会创建List<>。使用大括号时,您可以生成Dictionary<>

我通过将jSON字符串更改为:

解决了我的问题
{"1": {"11": {"1": 1,"2": 2,"3": 3},"21": {"1": 1,"2": 2,"3": 3},"31": {"1": 1,"2": 2,"3": 3}},"4": {"12": {"1": 1,"2": 2,"3": 3},"22": {"1": 1,"2": 2,"3": 3},"32": {"1": 1,"2": 2,"3": 3}},"6": {"13": {"1": 1,"2": 2,"3": 3},"23": {"1": 1,"2": 2,"3": 3},"33": {"1": 1,"2": 2,"3": 3}}}

并使用以下代码进行反序列化:

JsonConvert.DeserializeObject < Dictionary<int, Dictionary<int, Dictionary<int, int>>>>(jSONString)

这就是我生成三维数组的方法:

"{" + string.Join(",", dict.Select(a => String.Format("\"{0}\": {1}", a.Key, String.Join(",", "{" + String.Join(",", a.Value.Select(b => String.Format("\"{0}\": {1}", b.Key, String.Join(",", "{" + String.Join(",", b.Value.Select(c => String.Format("\"{0}\": {1}", c.Key, String.Join(",", c.Value)))) + "}")))) + "}")))) + "}"

1 个答案:

答案 0 :(得分:1)

当您尝试解析时,您的json不是 Dictionary<int, Dictionary<int, Dictionary<int, int>>>

Dictionary<int,List<Dictionary<int,List<List<int>>>>>

下面的代码可以使用,但这种结构不容易使用。


string json = @"{""1"": [{""11"": [[1, 1],[2, 2],[3, 3]],""21"": [[1, 1],[2, 2],[3, 3]],""31"": [[1, 1],[2, 2],[3, 3]]}],""4"": [{""12"": [[1, 1],[2, 2],[3, 3]],""22"": [[1, 1],[2, 2],[3, 3]],""32"": [[1, 1],[2, 2],[3, 3]]}],""6"": [{""13"": [[1, 1],[2, 2],[3, 3]],""23"": [[1, 1],[2, 2],[3, 3]],""33"": [[1, 1],[2, 2],[3, 3]]}]}";

var dict = JsonConvert.DeserializeObject<Dictionary<int,List<Dictionary<int,List<List<int>>>>>>(json);