如何在C#中将json转换为扁平结构

时间:2012-05-17 23:12:50

标签: c# json

我正在尝试用C#编写函数,将JSON转换为键/值对。它应该支持数组。例如,以下JSON:

{ 
    title: title_value,
    components: [
        {
            component_id: id1,
            menu: [
                   {title: menu_title1},
                   {title: menu_title_x},
                   {id: menu_id1}    
            ]
        },
        {
             component_id: id2,
             menu: [
                   {title: menu_title2},
                   {id: menu_id2}    
             ]
        }
    ]
}

应转换为:

  • title = title_value
  • components.0.component_id = id1
  • components.0.menu.0.title = menu_title1
  • components.0.menu.1.title = menu_title_x
  • components.0.menu.2.id = menu_id1
  • components.1.component_id = id2
  • components.1.menu.0.title = menu_title2
  • components.1.menu.1.id = menu_id2

这是完成此任务的简单方法吗?当我开始考虑数组和嵌套数组时,逻辑变得复杂。

2 个答案:

答案 0 :(得分:3)

我会调查http://json.codeplex.com/

我认为这就是你所需要的。

答案 1 :(得分:1)

解决方法如下。 JavaScriptSerializer从json字符串('json')创建对象('o'),而不是方法BuildVariablesList遍历对象并填充包含结果的字典('additionalParameters')。

    var jss = new JavaScriptSerializer();
    var o = return new DynamicJsonObject(jss.Deserialize<Dictionary<string, object>>(json));

    var additionalParameters = new Dictionary<string, string>();
    BuildVariablesList(o.GetInternalDictionary(), "", additionalParameters);

    private static string AppendToPathString (string path, object part )
    {
        return path.Trim().Length == 0 ? part.ToString() : path + '.' + part;
    }

    public static void BuildVariablesList(object obj, string path, Dictionary<string, string> result)
    {
        if ( obj is ArrayList)
        {
            var arrayObj = obj as ArrayList;
            for (var i = 0; i<arrayObj.Count; i++ )
            {
                BuildVariablesList(arrayObj[i], AppendToPathString(path,i), result);
            }
        }else if ( obj is Dictionary<string, object>)
        {
            var dictObject = obj as Dictionary<string, object>;
            foreach (var entry in dictObject)
            {
                if (entry.Value is String && (path.Trim().Length > 0 || !ReservedFieldNames.Contains( entry.Key.ToLower())))
                {
                    result.Add(AppendToPathString(path,entry.Key), entry.Value as String);
                }
                else if (entry.Value is Dictionary<string, object>)
                {
                    BuildVariablesList(entry.Value as Dictionary<string, object>, AppendToPathString(path, entry.Key), result);
                }
                else if (entry.Value is ArrayList)
                {
                    BuildVariablesList(entry.Value as ArrayList, AppendToPathString(path, entry.Key), result);
                }
            }
        }            
    }