/*--------------------------------------------------------------------------
* DynamicJson
* ver 1.2.0.0 (May. 21th, 2010)
*
* created and maintained by neuecc <ils@neue.cc>
* licensed under Microsoft Public License(Ms-PL)
* http://neue.cc/
* http://dynamicjson.codeplex.com/
*--------------------------------------------------------------------------*/
namespace Microshaoft
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml;
using System.Xml.Linq;
public class DynamicJson : DynamicObject
{
public object _value = null;
public object Value
{
get
{
if (_isValue)
{
return _value;
}
else
{
throw new Exception("It is not a Value!");
}
}
}
private bool _isValue = false;
public bool IsValue
{
get
{
return _isValue;
}
}
public T GetValue<T>()
{
return (T) Value;
}
public DynamicJson this[string key]
{
get
{
var x = xml.Element(key);
var value = default(dynamic);
var r = XElementToDynamicJson(x, out value);
if (r == null)
{
_value = value;
r = this;
_isValue = true;
}
return r;
}
}
public DynamicJson this[int index]
{
get
{
var x = xml
.Elements()
.ElementAt(index);
var value = default(dynamic);
var r = XElementToDynamicJson(x, out value);
if (r == null)
{
_value = value;
r = this;
_isValue = true;
}
return r;
}
}
private DynamicJson XElementToDynamicJson
(
XElement x
, out dynamic value
)
{
DynamicJson r = null;
if (TryGet(x, out value))
{
r = value as DynamicJson;
}
else
{
throw new Exception("no member");
}
return r;
}
private enum JsonType
{
@string, number, boolean, @object, array, @null
}
// public static methods
/// <summary>from JsonSring to DynamicJson</summary>
public static dynamic Parse(string json)
{
return Parse(json, Encoding.Unicode);
}
/// <summary>from JsonSring to DynamicJson</summary>
public static dynamic Parse(string json, Encoding encoding)
{
using (var reader = JsonReaderWriterFactory.CreateJsonReader(encoding.GetBytes(json), XmlDictionaryReaderQuotas.Max))
{
return ToValue(XElement.Load(reader));
}
}
/// <summary>from JsonSringStream to DynamicJson</summary>
public static dynamic Parse(Stream stream)
{
using (var reader = JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max))
{
return ToValue(XElement.Load(reader));
}
}
/// <summary>from JsonSringStream to DynamicJson</summary>
public static dynamic Parse(Stream stream, Encoding encoding)
{
using (var reader = JsonReaderWriterFactory.CreateJsonReader(stream, encoding, XmlDictionaryReaderQuotas.Max, _ => { }))
{
return ToValue(XElement.Load(reader));
}
}
/// <summary>create JsonSring from primitive or IEnumerable or Object({public property name:property value})</summary>
public static string Serialize(object obj)
{
return CreateJsonString(new XStreamingElement("root", CreateTypeAttr(GetJsonType(obj)), CreateJsonNode(obj)));
}
// private static methods
private static dynamic ToValue(XElement element)
{
var type = (JsonType)Enum.Parse(typeof(JsonType), element.Attribute("type").Value);
switch (type)
{
case JsonType.boolean:
return (bool)element;
case JsonType.number:
return (double)element;
case JsonType.@string:
return (string)element;
case JsonType.@object:
case JsonType.array:
return new DynamicJson(element, type);
case JsonType.@null:
default:
return null;
}
}
private static JsonType GetJsonType(object obj)
{
if (obj == null) return JsonType.@null;
switch (Type.GetTypeCode(obj.GetType()))
{
case TypeCode.Boolean:
return JsonType.boolean;
case TypeCode.String:
case TypeCode.Char:
case TypeCode.DateTime:
return JsonType.@string;
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.SByte:
case TypeCode.Byte:
return JsonType.number;
case TypeCode.Object:
return (obj is IEnumerable) ? JsonType.array : JsonType.@object;
case TypeCode.DBNull:
case TypeCode.Empty:
default:
return JsonType.@null;
}
}
private static XAttribute CreateTypeAttr(JsonType type)
{
return new XAttribute("type", type.ToString());
}
private static object CreateJsonNode(object obj)
{
var type = GetJsonType(obj);
switch (type)
{
case JsonType.@string:
case JsonType.number:
return obj;
case JsonType.boolean:
return obj.ToString().ToLower();
case JsonType.@object:
return CreateXObject(obj);
case JsonType.array:
return CreateXArray(obj as IEnumerable);
case JsonType.@null:
default:
return null;
}
}
private static IEnumerable<XStreamingElement> CreateXArray<T>(T obj) where T : IEnumerable
{
return obj.Cast<object>()
.Select(o => new XStreamingElement("item", CreateTypeAttr(GetJsonType(o)), CreateJsonNode(o)));
}
private static IEnumerable<XStreamingElement> CreateXObject(object obj)
{
return obj.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(pi => new { Name = pi.Name, Value = pi.GetValue(obj, null) })
.Select(a => new XStreamingElement(a.Name, CreateTypeAttr(GetJsonType(a.Value)), CreateJsonNode(a.Value)));
}
private static string CreateJsonString(XStreamingElement element)
{
using (var ms = new MemoryStream())
using (var writer = JsonReaderWriterFactory.CreateJsonWriter(ms, Encoding.Unicode))
{
element.WriteTo(writer);
writer.Flush();
return Encoding.Unicode.GetString(ms.ToArray());
}
}
// dynamic structure represents JavaScript Object/Array
readonly XElement xml;
readonly JsonType jsonType;
/// <summary>create blank JSObject</summary>
public DynamicJson()
{
xml = new XElement("root", CreateTypeAttr(JsonType.@object));
jsonType = JsonType.@object;
}
private DynamicJson(XElement element, JsonType type)
{
Debug.Assert(type == JsonType.array || type == JsonType.@object);
xml = element;
jsonType = type;
}
public bool IsObject { get { return jsonType == JsonType.@object; } }
public bool IsArray { get { return jsonType == JsonType.array; } }
/// <summary>has property or not</summary>
public bool IsDefined(string name)
{
return IsObject && (xml.Element(name) != null);
}
/// <summary>has property or not</summary>
public bool IsDefined(int index)
{
return IsArray && (xml.Elements().ElementAtOrDefault(index) != null);
}
/// <summary>delete property</summary>
public bool Delete(string name)
{
var elem = xml.Element(name);
if (elem != null)
{
elem.Remove();
return true;
}
else return false;
}
/// <summary>delete property</summary>
public bool Delete(int index)
{
var elem = xml.Elements().ElementAtOrDefault(index);
if (elem != null)
{
elem.Remove();
return true;
}
else return false;
}
/// <summary>mapping to Array or Class by Public PropertyName</summary>
public T Deserialize<T>()
{
return (T)Deserialize(typeof(T));
}
private object Deserialize(Type type)
{
return (IsArray) ? DeserializeArray(type) : DeserializeObject(type);
}
private dynamic DeserializeValue(XElement element, Type elementType)
{
var value = ToValue(element);
if (value is DynamicJson)
{
value = ((DynamicJson)value).Deserialize(elementType);
}
return Convert.ChangeType(value, elementType);
}
private object DeserializeObject(Type targetType)
{
var result = Activator.CreateInstance(targetType);
var dict = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanWrite)
.ToDictionary(pi => pi.Name, pi => pi);
foreach (var item in xml.Elements())
{
PropertyInfo propertyInfo;
if (!dict.TryGetValue(item.Name.LocalName, out propertyInfo)) continue;
var value = DeserializeValue(item, propertyInfo.PropertyType);
propertyInfo.SetValue(result, value, null);
}
return result;
}
private object DeserializeArray(Type targetType)
{
if (targetType.IsArray) // Foo[]
{
var elemType = targetType.GetElementType();
dynamic array = Array.CreateInstance(elemType, xml.Elements().Count());
var index = 0;
foreach (var item in xml.Elements())
{
array[index++] = DeserializeValue(item, elemType);
}
return array;
}
else // List<Foo>
{
var elemType = targetType.GetGenericArguments()[0];
dynamic list = Activator.CreateInstance(targetType);
foreach (var item in xml.Elements())
{
list.Add(DeserializeValue(item, elemType));
}
return list;
}
}
// Delete
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
result = (IsArray)
? Delete((int)args[0])
: Delete((string)args[0]);
return true;
}
// IsDefined, if has args then TryGetMember
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
if (args.Length > 0)
{
result = null;
return false;
}
result = IsDefined(binder.Name);
return true;
}
// Deserialize or foreach(IEnumerable)
public override bool TryConvert(ConvertBinder binder, out object result)
{
if (binder.Type == typeof(IEnumerable) || binder.Type == typeof(object[]))
{
var ie = (IsArray)
? xml.Elements().Select(x => ToValue(x))
: xml.Elements().Select(x => (dynamic)new KeyValuePair<string, object>(x.Name.LocalName, ToValue(x)));
result = (binder.Type == typeof(object[])) ? ie.ToArray() : ie;
}
else
{
result = Deserialize(binder.Type);
}
return true;
}
private bool TryGet(XElement element, out object result)
{
if (element == null)
{
result = null;
return false;
}
result = ToValue(element);
return true;
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
return (IsArray)
? TryGet(xml.Elements().ElementAtOrDefault((int)indexes[0]), out result)
: TryGet(xml.Element((string)indexes[0]), out result);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return (IsArray)
? TryGet(xml.Elements().ElementAtOrDefault(int.Parse(binder.Name)), out result)
: TryGet(xml.Element(binder.Name), out result);
}
private bool TrySet(string name, object value)
{
var type = GetJsonType(value);
var element = xml.Element(name);
if (element == null)
{
xml.Add(new XElement(name, CreateTypeAttr(type), CreateJsonNode(value)));
}
else
{
element.Attribute("type").Value = type.ToString();
element.ReplaceNodes(CreateJsonNode(value));
}
return true;
}
private bool TrySet(int index, object value)
{
var type = GetJsonType(value);
var e = xml.Elements().ElementAtOrDefault(index);
if (e == null)
{
xml.Add(new XElement("item", CreateTypeAttr(type), CreateJsonNode(value)));
}
else
{
e.Attribute("type").Value = type.ToString();
e.ReplaceNodes(CreateJsonNode(value));
}
return true;
}
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
return (IsArray)
? TrySet((int)indexes[0], value)
: TrySet((string)indexes[0], value);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
return (IsArray)
? TrySet(int.Parse(binder.Name), value)
: TrySet(binder.Name, value);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return (IsArray)
? xml.Elements().Select((x, i) => i.ToString())
: xml.Elements().Select(x => x.Name.LocalName);
}
/// <summary>Serialize to JsonString</summary>
public override string ToString()
{
// <foo type="null"></foo> is can't serialize. replace to <foo type="null" />
foreach (var elem in xml.Descendants().Where(x => x.Attribute("type").Value == "null"))
{
elem.RemoveNodes();
}
return CreateJsonString(new XStreamingElement("root", CreateTypeAttr(jsonType), xml.Elements()));
}
}
}
namespace ConsoleApplication1
{
using Microshaoft;
using System;
class Program
{
static void Main(string[] args)
{
DynamicJson dynamicJson = DynamicJson.Parse
(
@"
{
""foo"" : ""json""
, ""bar"" : 100
, ""nest"" :
[
{
""nest"" :
[
{ ""foobar"" : true }
, { ""foobar"" : false }
]
, ""foobar"" : true
}
,
{
""foobar"" : false
, ""array"" : [0,1,2,3]
}
]
}");
var x = dynamicJson["nest"][0]["nest"][1]["foobar"].Value;
Console.WriteLine(x);
var y = dynamicJson["nest"][1]["array"][3].Value;
Console.WriteLine(y);
Console.ReadLine();
}
}
}

Add Indexer to DynamicJson的更多相关文章

  1. kubernetes client-go解析

    注:本次使用的client-go版本为:client-go 11.0,主要参考CSDN上的深入浅出kubernetes之client-go系列,建议看本文前先参考该文档.本文档为CSDN文档的深挖和补 ...

  2. DynamicJson

    json字符串解析成Dynamic对象,开源地址http://dynamicjson.codeplex.com/,访问比较慢.使用方法摘录如下: Project Descriptiondynamic ...

  3. 背水一战 Windows 10 (18) - 绑定: 与 Element 绑定, 与 Indexer 绑定, TargetNullValue, FallbackValue

    [源码下载] 背水一战 Windows 10 (18) - 绑定: 与 Element 绑定, 与 Indexer 绑定, TargetNullValue, FallbackValue 作者:weba ...

  4. 绑定: 与 Element 绑定, 与 Indexer 绑定, TargetNullValue, FallbackValue

    介绍背水一战 Windows 10 之 绑定 与 Element 绑定 与 Indexer 绑定 TargetNullValue - 当绑定数据为 null 时显示的值 FallbackValue - ...

  5. 重新想象 Windows 8 Store Apps (52) - 绑定: 与 Element Model Indexer Style RelativeSource 绑定, 以及绑定中的数据转换

    [源码下载] 重新想象 Windows 8 Store Apps (52) - 绑定: 与 Element Model Indexer Style RelativeSource 绑定, 以及绑定中的数 ...

  6. solr6.3 + Hbase Indexer使用MR创建索引,错误Bad return type

    使用solr6.3 + Hbase Indexer ,通过Hbase-indexer从Hbase建立索引到solr中,进行全文搜索. 两种实现方式:① 开启hbase-indexer进行实时同步新数据 ...

  7. Splunk Enterprise architecture——转发器本质上是日志收集client附加负载均衡,indexer是分布式索引,外加一个集中式管理协调的中心节点

    Splunk Enterprise architecture and processes This topic discusses the internal architecture and proc ...

  8. c#编程指南(六) 类索引器(Class Indexer)

    类索引器,可以使得你使用数组一样的方式来访问类的数据. 这种访问多见于数组,列表,词典,哈希表的快捷访问. 实际上写法很简单,写成:public T1 this[T2 i] 代码如下: using S ...

  9. Kubernetes client-go Indexer / ThreadSafeStore 源码分析

    Kubernetes client-go Indexer / ThreadSafeStore 源码分析   请阅读原文:原文地址   Contents 概述 Indexer 接口 ThreadSafe ...

随机推荐

  1. 深入理解JSX

    本文由笔者翻译自官方文档的JSX In Depth,若干案例经过了改写.其实说白了也好像不算太深入,但还是提示了一些可能的盲区. JSX是为构造React元素方法React.createElement ...

  2. Could not find or load main class org.gradle.wrapper.GradleWrapperMain解决办法

    解决办法: gradlew is the gradle wrapper executable - batch script on windows and shell script elsewhere. ...

  3. HTML 5 胜出:XHTML2 宣告夭折

    自HTML 5 和XHTML 2规范草稿公布以来,一直存在很大的争议.HTML 5是由包括Google.Mirosoft.Mozilla.Opera.Apple在内多家浏览器厂商共同起草的下一代web ...

  4. sql注入时易被忽略的语法技巧以及二次注入

    那些容易被忽略.容易被弄错的地方 sql注入时的技巧 ========================================================================= ...

  5. MySQL的简单使用

    MySQL 参数     参数 描述 备注 -D,--database=.name 打开指定数据库 mysql –uroot –procky –Dhisdb 或者mysql –uroot –prock ...

  6. 谈谈混合 App Web 资源的打包与增量更新

    综述 移动 App 的运行环境具有带宽不稳定,流量收费,启动速度比较重要等特点,所以混合 App 如何加载 Web 资源并不是一个新问题.本文目的是总结出一种资源打包下载的思路和方案,并且提供一种打包 ...

  7. html 杂记

    <link rel="******"  href=“****.css” type=“text/css”  media=“screen” />css样式外部链接 加个斜杠 ...

  8. 在sql语句中使用 xml for path 格式化字符串的方法总结

    此方法实现的是将查询表中的某个字段,格式化成  字符串1,字符串2,字符串3...的格式 假设我们现在有两个表 分别是 分组表 grouped和分组成员表 groupuser grouped表有连个字 ...

  9. C#中的LINQ

    从自己的印象笔记里面整理出来,排版欠佳.见谅!   1.LINQ: 语言集成查询(Language Integrated Query) 实例: var q=      from c in catego ...

  10. Object类.

    equals方法. 比较的是内存地址.比较的是是否指向同一对象. toString:将对象转换成字符串. System.out.println()等价于  System.out.println(obj ...