internal bool _isArray = false;
///
/// 是否为json array类型
///
public bool IsArray
{
get { return _isArray; }
}
internal bool _isString = false;
///
/// 是否为json string类型
///
public bool IsString
{
get { return _isString; }
}
internal bool _isBool = false;
///
/// 是否为json bool类型
///
public bool IsBool
{
get { return _isBool; }
}
internal bool _isObject = false;
///
/// 是否为json object类型
///
public bool IsObject
{
get { return _isObject; }
}
internal bool _isChar = false;
///
/// 是否为json char类型
///
public bool IsChar
{
get { return _isChar; }
}
internal bool _isInt;
///
/// 是否为json 整数型
///
public bool IsInt
{
get { return _isInt; }
}
internal bool _isLong;
///
/// 是否为json 长整数型
///
public bool IsLong
{
get { return _isLong; }
}
internal bool _isDouble;
///
/// 是否为json 浮点型
///
public bool IsDouble
{
get { return _isDouble; }
}
internal bool _isNull = false;
///
/// 是否为json null
///
public bool IsNull
{
get { return _isNull; }
}
///
/// 将object转换为JsonObject
///
///
public JsonObject(object obj)
{
ConvertToJsonObject(this, obj);
}
///
/// 定义一个任意类型的隐式转换
///
///
///
public static implicit operator JsonObject(string obj)
{
return ImplicitConvert(obj);
}
public static implicit operator JsonObject(int obj)
{
return ImplicitConvert(obj);
}
public static implicit operator JsonObject(double obj)
{
return ImplicitConvert(obj);
}
public static implicit operator JsonObject(float obj)
{
return ImplicitConvert(obj);
}
public static implicit operator JsonObject(long obj)
{
return ImplicitConvert(obj);
}
public static implicit operator JsonObject(decimal obj)
{
return ImplicitConvert(obj);
}
private static JsonObject ImplicitConvert(object convert)
{
JsonObject obj = new JsonObject();
obj.ValueConvertToJsonObject(convert.ToString(), false);
return obj;
}
///
/// 转换形态
///
///
///
/// 如果是基本类型返回false直接进行设置
private bool ConvertToJsonObject(JsonObject parent, object sourceObj)
{
if (sourceObj == null)
return false;
Type t = sourceObj.GetType();
if (t.IsGenericType)
{
Type ctorType = t.GetGenericTypeDefinition();
if (ctorType == typeof(List))
{
parent._isArray = true;
parent._sourceObj = new List();
int count = (int)t.GetProperty("Count").GetValue(sourceObj, null);
MethodInfo get = t.GetMethod("get_Item");
for (int i = 0; i )
{
object value = get.Invoke(sourceObj, new object[] { i });
JsonObject innerObj = new JsonObject();
if (!ConvertToJsonObject(innerObj, value))
{
innerObj.ValueConvertToJsonObject(value.ToString(), false);
}
parent.add(innerObj);
}
}
else if (ctorType == typeof(Dictionary))
{
parent._isObject = true;
parent._sourceObj = new Dictionarystring, JsonObject>();
int count = (int)t.GetProperty("Count").GetValue(sourceObj, null);
object kv_entity = t.GetMethod("GetEnumerator").Invoke(sourceObj, null);
Type entityType = kv_entity.GetType();
for (int i = 0; i )
{
bool mNext = (bool)entityType.GetMethod("MoveNext").Invoke(kv_entity, null);
if (mNext)
{
object current = entityType.GetProperty("Current").GetValue(kv_entity, null);
Type currentType = current.GetType();
object key = currentType.GetProperty("Key").GetValue(current, null);
object value = currentType.GetProperty("Value").GetValue(current, null);
if (!(key is string))
throw new Exception("json规范格式不正确 Dictionary起始key应为string类型");
JsonObject innerObj = new JsonObject();
innerObj._key = key.ToString();
if (!ConvertToJsonObject(innerObj, value))
{
innerObj.ValueConvertToJsonObject(value.ToString(), false);
}
parent.add(innerObj);
}
}
}
else
{
throw new Exception("不支持的泛型操作");
}
return true;
}
else if (t.IsArray)
{
parent._isArray = true;
parent._sourceObj = new List();
int rank = t.GetArrayRank();
if (rank > 1)
{
throw new Exception("暂不支持超过1维的数组");
}
else
{
int length_info = Convert.ToInt32(t.GetProperty("Length").GetValue(sourceObj, null));
for (int i = 0; i )
{
object innerObj = t.GetMethod("GetValue", new Type[] { typeof(int) }).Invoke(sourceObj, new object[] { i });
JsonObject obj = new JsonObject();
if (!ConvertToJsonObject(obj, innerObj))
{
obj.ValueConvertToJsonObject(innerObj.ToString(), false);
}
parent.add(obj);
}
}
return true;
}
else if ((t.IsValueType && !t.IsPrimitive) || (t.IsClass && !(sourceObj is string)))
{
parent._isObject = true;
parent._sourceObj = new Dictionarystring, JsonObject>();
PropertyInfo[] infos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (PropertyInfo item in infos)
{
JsonObject innerObj = new JsonObject();
innerObj._key = item.Name;
object obj = item.GetValue(sourceObj, null);
if (!ConvertToJsonObject(innerObj, obj))
{
innerObj.ValueConvertToJsonObject(obj == null ? "null" : obj.ToString(), false);
}
parent.add(innerObj);
}
return true;
}
else
{
parent.ValueConvertToJsonObject(sourceObj.ToString(), false);
return false;
}
}
public JsonObject() { }
///
/// 如果为json object提取索引内容
///
/// key
///
public JsonObject this[string index]
{
get
{
if (IsObject)
{
if (ContainsKey(index))
{
return dictionary()[index];
}
else
{
throw new Exception("不包含 key: " + index);
}
}
else
{
throw new Exception("该对象不是一个json object类型请用IsObject进行验证后操作");
}
}
set
{
if (IsObject)
{
if (value is JsonObject)
{
dictionary()[index] = value;
}
else
{
dictionary()[index] = new JsonObject(value);
}
}
else
{
throw new Exception("该对象不是一个json object类型请用IsObject进行验证后操作");
}
}
}
///
/// 如果为json array提取索引内容
///
/// index
///
public JsonObject this[int index]
{
get
{
if (IsArray)
{
if (index >= Count || index 1)
throw new Exception("索引超出数组界限");
return array()[index];
}
else
{
throw new Exception("该对象不是一个json array类型请用IsArray进行验证后操作");
}
}
set
{
if (IsArray)
{
if (value is JsonObject)
{
array()[index] = value;
}
else
{
array()[index] = new JsonObject(value);
}
}
else
{
throw new Exception("该对象不是一个json array类型请用IsArray进行验证后操作");
}
}
}
///
/// 为json object 设置值如果存在则覆盖
///
///
///
public void Set(string key, object value)
{
if (IsObject)
{
Dictionarystring, JsonObject> objs = dictionary();
if (objs.ContainsKey(key))
{
if (value is JsonObject)
objs[key] = (JsonObject)value;
else
objs[key] = new JsonObject(value);
}
else
{
if (value is JsonObject)
objs.Add(key, (JsonObject)value);
else
objs.Add(key, new JsonObject(value));
}
}
else
{
this._isArray = false;
this._isBool = false;
this._isChar = false;
this._isDouble = false;
this._isInt = false;
this._isLong = false;
this._isNull = false;
this._isObject = true;
this._isString = false;
this._key = null;
this._sourceObj = new Dictionarystring, JsonObject>();
}
}
///
/// 为json object 设置值如果存在则覆盖
///
///
///
public void Set(string key, T value)
{
Set(key, value);
}
///
/// 为json array 添加值
///
///
///
public void Add(object value)
{
if (IsArray)
{
List objs = array();
if (value is JsonObject)
objs.Add((JsonObject)value);
else
objs.Add(new JsonObject(value));
}
else
{
this._isArray = true;
this._isBool = false;
this._isChar = false;
this._isDouble = false;
this._isInt = false;
this._isLong = false;
this._isNull = false;
this._isObject = false;
this._isString = false;
this._key = null;
this._sourceObj = new List();
}
}
///
/// 为json array 添加值
///
///
///
public void Add(T value)
{
Add(value);
}
///
/// 删除一个json object针对json object
///
///
public void Remove(string key)
{
if (this.IsObject)
{
dictionary().Remove(key);
}
}
///
/// 删除一个json object针对json array
///
///
public void Remove(int index)
{
if (this.IsArray)
{
array().RemoveAt(index);
}
}
///
/// 检测json object是否包含这个key
///
///
///
public bool ContainsKey(string key)
{
return dictionary().ContainsKey(key);
}
///
/// 获得json object或者json array的总数量
///
public int Count
{
get
{
if (IsArray)
return array().Count;
else if (IsObject)
return dictionary().Count;
return -1;
}
}
///
/// 将json object原始数据转换出去
///
///
public override string ToString()
{
return _sourceObj.ToString();
}
///
/// json key
///
internal string _key;
///
/// 源可替代为任何数据
/// Dictionary
/// List
/// String
/// Int
/// Double
/// Bool
/// 等
///
internal object _sourceObj;
///
/// 将源数据转换为json array
///
///
internal List array()
{
if (_sourceObj is List)
{
return (List)_sourceObj;
}
else
{
return null;
}
}
///
/// 将源数据转换为json dictionary
///
///
internal Dictionarystring, JsonObject> dictionary()
{
if (_sourceObj is Dictionarystring, JsonObject>)
{
return (Dictionarystring, JsonObject>)_sourceObj;
}
else
{
return null;
}
}
///
/// 封装了个简便的添加方法
///
///
internal void add(JsonObject obj)
{
if (this.IsObject)
{
Dictionarystring, JsonObject> objs = dictionary();
objs.Add(obj._key, obj);
}
else if (this.IsArray)
{
List objs = array();
objs.Add(obj);
}
}
///
/// 将json string 转换为对应的实体object
///
///
/// 判断是否来自逗号这样好验证格式不正常的string
internal void ValueConvertToJsonObject(string value, bool isFromComma)
{
//如果为string类型解析开始解析 json string
if (value is string)
{
string str = value.ToString();
bool isBaseType = false;
if (str.IndexOf(".") != -1)
{
//尝试解析double
double out_d = -1;
if (double.TryParse(str, out out_d))
{
isBaseType = true;
this._isDouble = true;
this._sourceObj = out_d;
}
}
else
{
//尝试解析长整数型
long out_l = -1;
if (long.TryParse(str, out out_l))
{
isBaseType = true;
//如果小于长整数 换算为整数类型
if (out_l int.MaxValue && out_l >= int.MinValue)
{
this._isInt = true;
_sourceObj = (int)out_l;
}
else
{
this._isLong = true;
_sourceObj = out_l;
}
}
}
if (!isBaseType)
{
if (str.ToLower().Equals("null"))
{
this._isNull = true;
}
else if (str.ToLower().Equals("true") || str.ToLower().Equals("false"))
{
this._isBool = true;
this._sourceObj = bool.Parse(str.ToLower());
}
else
{
if (!isFromComma)
{
this._isString = true;
int idx = str.IndexOf("\\u");
while (idx != -1)
{
string v = str.Substring(idx, 6);
string hex1 = v.Substring(2, 2);
string hex2 = v.Substring(4);
byte[] bytes = new byte[2] {
Convert.ToByte(hex2,16),
Convert.ToByte(hex1,16)
};
str = str.Replace(v, Encoding.Unicode.GetString(bytes));
idx = str.IndexOf("\\u");
}
_sourceObj = str;
}
else
{
throw new Exception("json字符串格式有误 请加单引号或双引号");
}
}
}
}
}
///
/// 直接返回源数据
///
///
public object ToObject()
{
return _sourceObj;
}
///
/// 转换为json串
///
///
public string ToJson()
{
StringBuilder sb = new StringBuilder();
if (IsObject)
{
sb.Append("{");
Dictionarystring, JsonObject> objs = dictionary();
Liststring> keys = new Liststring>(objs.Keys);
int i;
for (i = 0; i 1; i++)
{
sb.Append("\"");
sb.Append(keys[i]);
sb.Append("\":");
sb.Append(objs[keys[i]].ToJson());
sb.Append(",");
}
sb.Append("\"");
sb.Append(keys[i]);
sb.Append("\":");
sb.Append(objs[keys[i]].ToJson());
sb.Append("}");
}
else if (IsArray)
{
sb.Append("[");
List objs = array();
int i;
for (i = 0; i 1; i++)
{
sb.Append(objs[i].ToJson());
sb.Append(",");
}
sb.Append(objs[i].ToJson());
sb.Append("]");
}
else
{
if (!IsString)
{
if (IsBool)
{
sb.Append(((bool)_sourceObj) ? "true" : "false");
}
else if (IsNull)
{
sb.Append("null");
}
else
{
sb.Append(_sourceObj);
}
}
else
{
sb.Append("\"");
sb.Append(_sourceObj);
sb.Append("\"");
}
}
return sb.ToString();
}
///
/// 将jsonobject转换为实体object
/// 有参的
///
/// 实体object类型
/// 构造参数
///
public T ToObject(params object[] ctor)
{
object targetObj = null;
if (this.IsObject || this.IsArray)
{
Type targetObjType = typeof(T);
targetObj = CreateObject(targetObjType, ctor);
}
return (T)ConvertToObject(targetObj, this);
}
///
/// 将jsonobject转换为实体object
/// 无参的
///
/// 实体构造类型
///
public T ToObject()
{
return ToObject(null);
}
private object ConvertToObject(object targetObj, JsonObject obj)
{
Type targetType = null;
if (targetObj != null)
targetType = targetObj.GetType();
//判断下object
if (obj.IsObject)
{
Dictionarystring, JsonObject> dictionarys = obj.dictionary();
Dictionarystring, JsonObject>.Enumerator enumerator = dictionarys.GetEnumerator();
while (enumerator.MoveNext())
{
string key = enumerator.Current.Key;
JsonObject value = enumerator.Current.Value;
PropertyInfo info = targetType.GetProperty(key, BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public);
if (targetType.IsGenericType)
{
if (targetType.GetGenericTypeDefinition() == typeof(Dictionary))
{
object setInnerValue = null;
Type innerValueType = targetType.GetGenericArguments()[1];
setInnerValue = GetJsonObjectEntity(innerValueType, value);
setInnerValue = ConvertToObject(setInnerValue, value);
MethodInfo add_info = targetType.GetMethod("Add");
add_info.Invoke(targetObj, new object[] { key, setInnerValue });
}
else
{
throw new Exception("\"" + targetType.Name + "\"属性 \"" + key + "\"不是Dictionary泛型类型");
}
}
else if (info != null)
{
object innerObj = info.GetValue(targetObj, null);
if (innerObj == null)
innerObj = GetJsonObjectEntity(info.PropertyType, value);
innerObj = ConvertToObject(innerObj, value);
info.SetValue(targetObj, innerObj, null);
}
else
{
throw new Exception("\"" + targetType.Name + "\"类中找不到属性 \"" + key + "\"无法完成转换操作");
}
}
}
else if (obj.IsArray)
{
List arrays = obj.array();
for (int i = 0; i )
{
JsonObject item = arrays[i];
if (targetType.IsGenericType)
{
Type[] types = targetType.GetGenericArguments();
Type objType = types[0];
object innerObj = GetJsonObjectEntity(objType, item);
innerObj = ConvertToObject(innerObj, item);
MethodInfo info = targetType.GetMethod("Add");
info.Invoke(targetObj, new object[] { innerObj });
}
else if (targetType.IsArray)
{
object innerObj = GetJsonObjectEntity(targetType, item);
innerObj = ConvertToObject(innerObj, item);
MethodInfo info = targetType.GetMethod("SetValue", new Type[] { typeof(object), typeof(int) });
info.Invoke(targetObj, new object[] { innerObj, i });
}
}
}
else
{
return obj._sourceObj;
}
return targetObj;
}
private object GetJsonObjectEntity(Type type, JsonObject value)
{
object innerObj = null;
if (value.IsObject && innerObj == null)
{
innerObj = CreateObject(type, null);
}
else if (value.IsArray)
{
if (innerObj == null)
{
if (type.IsGenericType)
{
innerObj = CreateObject(type, null);
}
else if (type.IsArray)
{
if (type.GetArrayRank() > 1)
{
throw new Exception("暂不支持1维数组以上的数据类型");
}
innerObj = type.InvokeMember("Set", BindingFlags.CreateInstance, null, null, new object[] { value.Count });
}
}
}
return innerObj;
}
private object CreateObject(Type objType, params object[] ctor)
{
try
{
object targetObj;
if (ctor == null)
targetObj = Activator.CreateInstance(objType);
else
targetObj = Activator.CreateInstance(objType, ctor);
return targetObj;
}
catch (Exception ex)
{
throw new Exception("构造\"" + objType.FullName + "\"过程中出现异常 可能是类构造函数异常也可能是其他的异常 详细参见InnerException", ex);
}
}