首页 > 学院 > 开发设计 > 正文

C#深入解析Json格式内容

2019-11-17 02:47:11
字体:
来源:转载
供稿:网友

C#深入解析Json格式内容

继上一篇《浅谈C#手动解析Json格式内容》我又来分析加入了一些功能让 这个解析类更实用

本章节最会开放我最终制作成功的Anonymous.Json.dll这个解析库 需要的拿走~

功能继上一篇增加了许多上一篇只是讲述了 解析的步骤但是 至于一些扩展的功能却没有涉及

本文将继续讲解

1.如何将json转换为一个类或者结构 甚至属性

2.如何将一个类或者结构甚至属性转换为json

就这两点就已经很头疼了 诶 废话不多说进入正题

上一篇一直有个很神秘的JsonObject没有讲解 现在先来揭开JsonObject的神秘面纱

internal bool _isArray = false;/// <summary>/// 是否为json array类型/// </summary>public bool IsArray{    get { return _isArray; }}internal bool _isString = false;/// <summary>/// 是否为json string类型/// </summary>public bool IsString{    get { return _isString; }}internal bool _isBool = false;/// <summary>/// 是否为json bool类型/// </summary>public bool IsBool{    get { return _isBool; }}internal bool _isObject = false;/// <summary>/// 是否为json object类型/// </summary>public bool IsObject{    get { return _isObject; }}internal bool _isChar = false;/// <summary>/// 是否为json char类型/// </summary>public bool IsChar{    get { return _isChar; }}internal bool _isInt;/// <summary>/// 是否为json 整数型/// </summary>public bool IsInt{    get { return _isInt; }}internal bool _isLong;/// <summary>/// 是否为json 长整数型/// </summary>public bool IsLong{    get { return _isLong; }}internal bool _isDouble;/// <summary>/// 是否为json 浮点型/// </summary>public bool IsDouble{    get { return _isDouble; }}internal bool _isNull = false;/// <summary>/// 是否为json null/// </summary>public bool IsNull{    get { return _isNull; }}/// <summary>/// 将object转换为JsonObject/// </summary>/// <param name="obj"></param>public JsonObject(object obj){    ConvertToJsonObject(this, obj);}/// <summary>/// 定义一个任意类型的隐式转换/// </summary>/// <param name="obj"></param>/// <returns></returns>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;}/// <summary>/// 转换形态/// </summary>/// <param name="parent"></param>/// <param name="sourceObj"></param>/// <returns>如果是基本类型返回false直接进行设置</returns>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<JsonObject>();            int count = (int)t.GetProperty("Count").GetValue(sourceObj, null);            MethodInfo get = t.GetMethod("get_Item");            for (int i = 0; i < count; 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 Dictionary<string, 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 < count; 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<JsonObject>();        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 < length_info; 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 Dictionary<string, 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() { }/// <summary>/// 如果为json object提取索引内容/// </summary>/// <param name="index">key</param>/// <returns></returns>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 Except
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表