Advertisement
L_B

Dynamic Json Object

L_B
Nov 2nd, 2011
10,919
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.88 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Xml.Linq;
  6. using System.Text;
  7. using System.IO;
  8. using System.Dynamic;
  9.  
  10. using Newtonsoft.Json;
  11. using Newtonsoft.Json.Linq;
  12. using Newtonsoft.Json.Serialization;
  13.  
  14.  
  15. ///////////////////////////////////////////////////////////////////////
  16. // Needs JSon.Net (Newtonsoft.Json.dll) from http://json.codeplex.com/
  17. //////////////////////////////////////////////////////////////////////
  18.  
  19. namespace JsonUtils
  20. {
  21.     /// <summary>
  22.     /// Creates a dynamic object
  23.     /// Methods that can be used on arrays: foreach, ToArray(), ToList(), Count, Length
  24.     /// </summary>
  25.     public class JsonObject : DynamicObject, IEnumerable, IEnumerator
  26.     {
  27.         object _object;
  28.        
  29.         JsonObject(object jObject)
  30.         {
  31.             this._object = jObject;
  32.         }
  33.  
  34.         public static dynamic GetDynamicJsonObject(byte[] buf)
  35.         {
  36.             return GetDynamicJsonObject(buf, Encoding.UTF8);
  37.         }
  38.  
  39.         public static dynamic GetDynamicJsonObject(byte[] buf, Encoding encoding)
  40.         {
  41.             return GetDynamicJsonObject(encoding.GetString(buf));
  42.         }
  43.  
  44.         public static dynamic GetDynamicJsonObject(string json)
  45.         {
  46.             object o = JsonConvert.DeserializeObject(json);
  47.             return new JsonUtils.JsonObject(o);
  48.         }
  49.  
  50.         internal static dynamic GetDynamicJsonObject(JObject jObj)
  51.         {
  52.             return new JsonUtils.JsonObject(jObj);
  53.         }
  54.  
  55.         public object this[string s]
  56.         {
  57.             get
  58.             {
  59.                 JObject jObject = _object as JObject;
  60.                 object obj = jObject.SelectToken(s);
  61.                 if (obj == null) return true;
  62.  
  63.                 if (obj is JValue)
  64.                     return GetValue(obj);
  65.                 else
  66.                     return new JsonObject(obj);
  67.             }
  68.         }
  69.  
  70.         public object this[int i]
  71.         {
  72.             get
  73.             {
  74.                 if (!(_object is JArray)) return null;
  75.  
  76.                 object obj = (_object as JArray)[i];
  77.                 if (obj is JValue)
  78.                 {
  79.                     return GetValue(obj);
  80.                 }
  81.                 return new JsonObject(obj);
  82.             }
  83.         }
  84.  
  85.         public override bool TryGetMember(GetMemberBinder binder, out object result)
  86.         {
  87.             result = null;
  88.  
  89.             if (_object is JArray)
  90.             {
  91.                 JArray jArray = _object as JArray;
  92.                 switch (binder.Name)
  93.                 {
  94.                     case "Length":
  95.                     case "Count": result = jArray.Count; break;
  96.                     case "ToList": result = (Func<List<string>>)(() => jArray.Values().Select(x => x.ToString()).ToList()); break;
  97.                     case "ToArray": result = (Func<string[]>)(() => jArray.Values().Select(x => x.ToString()).ToArray()); break;
  98.                 }
  99.  
  100.                 return true;
  101.             }
  102.  
  103.             JObject jObject = _object as JObject;
  104.             object obj = jObject.SelectToken(binder.Name);
  105.             if (obj == null) return true;
  106.  
  107.             if (obj is JValue)
  108.                 result = GetValue(obj);
  109.             else
  110.                 result = new JsonObject(obj);
  111.  
  112.             return true;
  113.         }
  114.  
  115.         object GetValue(object obj)
  116.         {
  117.             string val = ((JValue)obj).ToString();
  118.  
  119.             int resInt; double resDouble; DateTime resDateTime;
  120.  
  121.             if (int.TryParse(val, out resInt)) return resInt;
  122.             if (DateTime.TryParse(val, out resDateTime)) return resDateTime;
  123.             if (double.TryParse(val, out resDouble)) return resDouble;
  124.            
  125.             return val;
  126.         }
  127.  
  128.         public override string ToString()
  129.         {
  130.             return _object.ToString();
  131.         }
  132.  
  133.         int _index = -1;
  134.  
  135.         public IEnumerator GetEnumerator()
  136.         {
  137.             _index = -1;
  138.             return this;
  139.         }
  140.  
  141.         public object Current
  142.         {
  143.             get
  144.             {
  145.                 if (!(_object is JArray)) return null;
  146.                 object obj = (_object as JArray)[_index];
  147.                 if (obj is JValue) return GetValue(obj);
  148.                 return new JsonObject(obj);
  149.             }
  150.         }
  151.  
  152.         public bool MoveNext()
  153.         {
  154.             if (!(_object is JArray)) return false;
  155.             _index++;
  156.             return _index < (_object as JArray).Count;
  157.         }
  158.  
  159.         public void Reset()
  160.         {
  161.             throw new NotImplementedException();
  162.         }
  163.     }
  164.  
  165.     public class XmlObject
  166.     {
  167.         public static dynamic GetDynamicJsonObject(string xmlString)
  168.         {
  169.             var xmlDoc = XDocument.Load(new StringReader(xmlString));
  170.             return JsonObject.GetDynamicJsonObject(XmlToJObject(xmlDoc.Root));
  171.         }
  172.  
  173.         public static dynamic GetDynamicJsonObject(Stream xmlStream)
  174.         {
  175.             var xmlDoc = XDocument.Load(xmlStream);
  176.             return JsonObject.GetDynamicJsonObject(XmlToJObject(xmlDoc.Root));
  177.         }
  178.  
  179.         static JObject XmlToJObject(XElement node)
  180.         {
  181.             JObject jObj = new JObject();
  182.             foreach (var attr in node.Attributes())
  183.             {
  184.                 jObj.Add(attr.Name.LocalName, attr.Value);
  185.             }
  186.  
  187.             foreach (var childs in node.Elements().GroupBy(x => x.Name.LocalName))
  188.             {
  189.                 string name = childs.ElementAt(0).Name.LocalName;
  190.                 if (childs.Count() > 1)
  191.                 {
  192.                     JArray jArray = new JArray();
  193.                     foreach (var child in childs)
  194.                     {
  195.                         jArray.Add(XmlToJObject(child));
  196.                     }
  197.                     jObj.Add(name, jArray);
  198.                 }
  199.                 else
  200.                 {
  201.                     jObj.Add(name, XmlToJObject(childs.ElementAt(0)));
  202.                 }
  203.             }
  204.  
  205.             node.Elements().Remove();
  206.             if (!String.IsNullOrEmpty(node.Value))
  207.             {
  208.                 string name = "Value";
  209.                 while (jObj[name] != null) name = "_" + name;
  210.                 jObj.Add(name, node.Value);
  211.             }
  212.  
  213.             return jObj;
  214.         }
  215.     }
  216. }
  217.  
  218. namespace System
  219. {
  220.     public static class JsonExtensions
  221.     {                                      
  222.         public static JsonUtils.JsonObject GetDynamicJsonObject(this Uri uri)
  223.         {
  224.             using(Net.WebClient wc = new Net.WebClient())
  225.             {
  226.                 wc.Encoding = System.Text.Encoding.UTF8;
  227.                 wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";
  228.                 return JsonUtils.JsonObject.GetDynamicJsonObject(wc.DownloadString(uri.ToString()));
  229.             }
  230.         }
  231.     }
  232. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement