How to convert json to flat structure in c #

I am trying to write a function in C # that converts JSON to key / value pairs. It must support arrays. So, for example, the following 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} ] } ] } 

should be converted to:

  • 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

Is this an easy way to complete this task? The logic gets complicated when I start to take into account arrays and nested arrays.

+7
source share
2 answers

The solution for this is as follows. The JavaScriptSerializer creates an object ('o') from a json string ('json'), than the BuildVariablesList method intersects the object and populates a dictionary ('optional parameters') that contains the results.

  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); } } } } 
+1
source

I would look at http://json.codeplex.com/

I think that does what you need.

+3
source

All Articles