private static dynamic GetObject(JObject jobj) { var obj = new FriendlyDynamic() as IDictionary <string, object>; foreach (var pair in jobj) { obj.Add(pair.Key.Replace('-', '_'), GetValue(pair.Value)); } return(obj); }
public static dynamic Parse(XDocument xml) { var result = new FriendlyDynamic() as IDictionary <string, object>; var root = xml.Root; AddElement(root, result); return(result); }
private static bool CanCompact(FriendlyDynamic dyn) { if (dyn._dictionary.Count > 5) { return(false); } foreach (var pair in dyn._dictionary) { if (!CanCompact(pair.Value)) { return(false); } } return(true); }
private static string DynamicToString(FriendlyDynamic dyn, int level, bool insideList) { var canCompact = (level < 2 || insideList) && CanCompact(dyn); var str = "{"; str += canCompact ? " " : "\r\n"; var i = 0; foreach (var pair in dyn._dictionary) { str += PairToString(pair, level + 1, canCompact); if (i < dyn._dictionary.Count - 1) { str += "," + (canCompact ? " " : ""); } str += canCompact ? "" : "\r\n"; i++; } str += (canCompact ? " " : Indent(level)) + "}"; return(str); }
private static void AddElement(XElement el, IDictionary <string, object> parent) { var name = el.Name.LocalName; // check for multiple elements with the same name and convert to list var addToList = parent.ContainsKey(name); IList <dynamic> list = null; if (addToList) { var container = parent[name]; list = container as IList <dynamic>; if (list == null) { // convert to list list = new List <dynamic>(new dynamic[] { container }); parent[name] = list; } } if (el.HasElements || el.HasAttributes) // complex object { var obj = new FriendlyDynamic() as IDictionary <string, object>; if (addToList) { list.Add(obj); } else { parent[name] = obj; } foreach (var attr in el.Attributes()) { obj[attr.Name.LocalName] = attr.Value; } foreach (var child in el.Elements()) { AddElement(child, obj); } if (!el.HasElements && !el.IsEmpty) { var valName = Char.IsUpper(name[0]) ? "Text" : "text"; // mimic case obj[valName] = el.Value; } } else // simple value { if (addToList) { list.Add(el.Value); } else { parent[name] = el.Value; } } }