阿赵Json工具AzhaoJson的C#版本

  大家好,我是阿赵。
  Json解析的工具网上有很多,其实也没什么必要自己写。不过作为一个程序员,在写代码的时候总希望能有一些比较顺手的工具类可以自定义使用。比如我很久之前写的3d引擎,模型格式也是自己定义的azhao3d格式,就是喜欢这种自由奔放需要什么就有什么的感觉。这个AzhaoJson,是我很多年之前写的,用了这么多年,感觉还不错,这里和大家分享一下。这个AzhaoJson有C#版本和Lua版本,这次分享一下C#的版本。
  作为工具的对外入口类,Json这个类主要提供了2个方法,分别是ToJson和ToObject。

using System;

namespace AzhaoJson
{
    public class Json
    {
        /// <summary>
        /// 把对象转成字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        static public string ToJson(object obj)
        {
            return JsonTools.GetObjectString(obj);
        }
        /// <summary>
        /// 把对象转成字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        static public string ToJson(JsonData obj)
        {
            return JsonTools.GetStringByJD(obj);
        }

        /// <summary>
        /// 把字符串转成对象
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        static public JsonData ToObject(string str)
        {
            try
            {
                str = JsonTools.TrimStr(str);
                JsonObject obj = new JsonObject();
                return obj.GetJsonData(str);
            }
            catch(Exception ex)
            {
                return null;
            }
        }


        /// <summary>
        /// 根据类型把字符串转成类的实例对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        static public T ToObject<T>(string str) where T : class
        {
            JsonData jd = ToObject(str);
            if (jd != null)
            {
                Type type = typeof(T);
                return (T)JsonTools.GetObjectByType(type, jd);
            }
            else
            {
                return null;
            }
        }       

    }
}

  由于C#是强类型的,所以在不指定类对象类型时,我封装了一个JsonData的类作为Json解析的对象。
1.ToJson
  ToJson方法是把对象转换成Json字符串的方法,有2种重载,分别是可以传入object对象,或者传入JsonData对象。
  使用举例:
  假设我这里有一些自定义类,然后构建了对象,这里可以把它转换成Json字符串:

    TestSaveData data = new TestSaveData();
    data.dict = new Dictionary<int, TestClass1>();
    TestClass1 sd = new TestClass1();
    sd.id = 1;
    sd.name = "aaa";
    sd.AddNewValue(2);
    data.dict.Add(1, sd);
    string content = Json.ToJson(data);

这时候打印content,就能得到json字符串:

{“dict”:{1:{“id”:1,“name”:“aaa”,“x”:0,“y”:0,“isShow”:true,“testList”:[{“fromId”:1,“toId”:2,“time”:0}]}}}

  由于我一般都是用于数据存储,所以并没有对Json字符串进行格式化处理,所以阅读性会差一点。
2.ToObject
  ToObject方法可以把Json字符串转换成对象。可以转换成JsonData的对象,也可以传入泛型,返回指定的对象。
  使用举例:
  就以刚才转换出来的Json字符串为例:
  如果转换成JsonData,会是这样:

    JsonData jd = Json.ToObject(content);
    JsonData dictObj1 = jd["dict"];
    JsonData dictObj2 = dictObj1[1f];
    string objName = dictObj2["name"].ToString();

需要注意的是,由于刚才那个对象生成的时候,dict里面是用数字1作为key的,从字符串转回Json对象的时候,不知道这个1究竟是整型还是浮点,所以统一当做浮点,所以取值的时候,需要加上f代表是浮点。
  实际上我自己在使用的时候,很少会转成JsonData的,因为我使用这个Json的时候,一般是用于工具的数据保存和还原,所以数据本身都是有很明确的类的。于是,真正用得多的是使用泛型:

TestSaveData data = AzhaoJson.Json.ToObject<TestSaveData>(content);
string objName = data.dict[1].name;

  使用就是这么简单。
下面附带一下其他几个脚本的源码:
DataType.cs:

namespace AzhaoJson
{
    public class DataType
    {
        /// <summary>
        /// 数字类型
        /// </summary>
        public const string NUMBER = "number";
        /// <summary>
        /// 字符串类型
        /// </summary>
        public const string STRING = "string";
        /// <summary>
        /// 布尔类型
        /// </summary>
        public const string BOOL = "bool";
        /// <summary>
        /// 数组类型
        /// </summary>
        public const string ARRAY = "array";
        /// <summary>
        /// 字典类型
        /// </summary>
        public const string DICTIONARY = "dictionary";
        /// <summary>
        /// 对象类型
        /// </summary>
        public const string OBJECT = "object";
        /// <summary>
        /// 其他
        /// </summary>
        public const string OTHER = "other";
    }
}

JsonData.cs:

using System;
using System.Collections.Generic;

namespace AzhaoJson
{
    public class JsonData
    {
        private string _type = "";

        public string Type
        {
            get { 
                return _type; 
            }

        }
        private int _count = 0;

        public int Count
        {
            get { return _count; }
        }
        private object content;
        private Dictionary<object, JsonData> contentDict;
        private List<string> keys = new List<string>();

        public JsonData()
        {
            contentDict = new Dictionary<object, JsonData>();
        }
        /// <summary>
        /// 设置当前JsonData的类型
        /// </summary>
        /// <param name="t"></param>
        public void SetType(string t)
        {
            _type = t;
        }
        /// <summary>
        /// 设置当前JsonData的值
        /// </summary>
        /// <param name="obj"></param>
        public void SetValue(object obj)
        {
            content = obj;
            _type = GetTypeByObj(obj);
        }
        /// <summary>
        /// 通过数组设置当前JsonData的值
        /// </summary>
        /// <param name="objs"></param>
        public void SetValue(JsonData[] objs)
        {

            _type = DataType.ARRAY;
            _count = 0;
            if(objs!=null&&objs.Length>0)
            {
                _count = objs.Length;
                for(int i = 0;i<objs.Length;i++)
                {
                    SetValue(i, objs[i]);
                }
            }            
        }
        /// <summary>
        /// 通过List设置当前JsonData的值
        /// </summary>
        /// <param name="objs"></param>
        public void SetValue(List<JsonData> objs)
        {
            _count = 0;
            _type = DataType.ARRAY;
            if(objs!=null&&objs.Count>0)
            {
                _count = objs.Count;
                for (int i = 0; i < objs.Count; i++)
                {
                    SetValue(i,objs[i]);
                }
            }


        }
        /// <summary>
        /// 通过key、value设置当前JsonData的值
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">key对应的值</param>
        public void SetValue(object key,JsonData value)
        {
            if(contentDict.ContainsKey(key))
            {
                contentDict[key] = value;
            }
            else
            {
                contentDict.Add(key, value);
            }
            string ks = key.ToString();
            if(keys.IndexOf(ks)<0)
            {
                keys.Add(ks);
            }
        }

        /// <summary>
        /// 判断传入内容的类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private string GetTypeByObj(object obj)
        {
            Type type = obj.GetType();

            return JsonTools.GetDataType(type);
        }

        /// <summary>
        /// 取某个key的值,返回jsonData
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>key对应的值</returns>
        public JsonData Get(object key)
        {
            if(contentDict.ContainsKey(key))
            {
                return contentDict[key];
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>key对应的值</returns>
        public JsonData this[object key]
        {
            get{
                if (contentDict.ContainsKey(key))
                {
                    return contentDict[key];
                }
                else
                {
                    return null;
                }
            }
            set
            {

                if (contentDict.ContainsKey(key))
                {
                    contentDict[key] = value;
                }
                else
                {
                    contentDict.Add(key, value);
                }
            }   
        }

        /// <summary>
        /// 获得当前JsonData对象的
        /// </summary>
        /// <returns></returns>

        public object ToValue()
        {
            if(_type == DataType.ARRAY)
            {
                return GetList();
            }
            else if(_type == DataType.BOOL)
            {
                return ToBool();
            }
            else if(_type == DataType.NUMBER)
            {
                return ToFloat();
            }
            else if(_type == DataType.STRING)
            {
                return ToString();
            }
            else
            {
                return ToString();
            }
        }

        /// <summary>
        /// 把值转成string字符串
        /// </summary>
        /// <returns></returns>
        public string ToString()
        {
            if(content!=null)
            {
                return content.ToString();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 把值转成整型
        /// </summary>
        /// <returns></returns>
        public int ToInt()
        {
            if (content != null)
            {
                return int.Parse(content.ToString());
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 把值转成浮点数值
        /// </summary>
        /// <returns></returns>
        public float ToFloat()
        {
            if (content != null)
            {
                return float.Parse(content.ToString());
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 把值转成布尔
        /// </summary>
        /// <returns></returns>
        public bool ToBool()
        {
            if (content != null)
            {
                string b = content.ToString().ToLower();
                if(b=="true")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取该JsonData的所有key
        /// </summary>
        /// <returns></returns>
        public List<string> GetKeys()
        {
            if(_type!=DataType.OBJECT)
            {
                return null;
            }
            return keys;
        }

        public Dictionary<object,JsonData> GetObjDict()
        {
            if(contentDict== null)
            {
                return null;
            }
            else
            {
                return contentDict;
            }
        }

        /// <summary>
        /// 获取该JsonData的数组值
        /// </summary>
        /// <returns></returns>
        public List<JsonData> GetList()
        {
            if(_type!=DataType.ARRAY)
            {
                return null;
            }
            List<JsonData> list = new List<JsonData>();
            if(content!=null)
            {
                Array arr = content as Array;
                if(arr!=null)
                {
                    foreach(System.Object ob in arr)
                    {
                        JsonData js = new JsonData();
                        js.SetValue(ob);
                        list.Add(js);
                    }
                    return list;
                }
            }
            for(int i = 0;i<_count;i++)
            {
                if(contentDict.ContainsKey(i))
                {
                    list.Add(contentDict[i]);
                }      
            }
            return list;
        }


    }
}

JsonObject.cs

using System.Collections.Generic;

namespace AzhaoJson
{
    public class JsonObject
    {
        private string orgStr;
        private int len;
        private int curPos;
        private string token;
        public JsonData GetJsonData(string str)
        {
            curPos = 0;
            orgStr = str;
            len = str.Length;
            token = ReadUnSpace();
            if (token == "{")
            {
                return GetObject();
            }

            return null;
        }

        private JsonData GetObject()
        {
            JsonData jd = new JsonData();
            jd.SetType(DataType.OBJECT);
            while (token == " ")
            {
                token = Read();
            }
            while (token != "}" && curPos < len && !string.IsNullOrEmpty(token))
            {
                if (token != ",")
                {
                    object key = GetKey();
                    if(key.GetType() == typeof(string))
                    {
                        string keyStr = (string)key;
                        keyStr = keyStr.Trim();
                        if (string.IsNullOrEmpty(keyStr))
                        {
                            break;
                        }
                        JsonData v = GetValue();
                        jd.SetValue(keyStr, v);
                    }
                    else
                    {
                        if(key == null)
                        {
                            break;
                        }
                        JsonData v = GetValue();
                        jd.SetValue(key, v);
                    }
                }
                token = ReadUnSpace();
            }

            return jd;

        }

        private JsonData GetArray()
        {
            List<JsonData> list = new List<JsonData>();
            JsonData jd = new JsonData();
            token = ReadUnSpace();
            while (token != "]" && !string.IsNullOrEmpty(token))
            {
                if (token == "{")
                {
                    list.Add(GetObject());
                }
                else if (token == "[")
                {
                    list.Add(GetArray());
                }
                else if (token != ",")
                {
                    JsonData arrJd = GetFinalValue();
                    if (arrJd != null)
                    {
                        list.Add(arrJd);
                    }
                }
                token = ReadUnSpace();
            }
            jd.SetValue(list);
            return jd;
        }

        private object GetKey()
        {
            string k = "";
            bool isString = false;
            while (token != ":" && token != "}" && !string.IsNullOrEmpty(token))
            {
                if (token != "\"" && token != "{")
                {
                    k += token;
                }
                else
                {
                    if(token == "\"")
                    {
                        isString = true;
                    }                    
                }
                token = Read();
            }
            if(isString == true)
            {
                return k;
            }
            else
            {
                float val = 0;
                float.TryParse(k,out val);
                return val;
            }
            return k;

        }

        private JsonData GetValue()
        {
            token = ReadUnSpace();
            if (token == "{")
            {
                return GetObject();
            }
            else if (token == "[")
            {
                return GetArray();
            }
            else
            {
                return GetFinalValue();
            }
        }

        private JsonData GetFinalValue()
        {
            JsonData jd = new JsonData();
            string k = "";
            string t = token;
            string addStr = "";//= GetString();

            if (t == "\"")
            {
                addStr = GetStringValue();
                jd.SetValue(addStr);
            }
            else
            {
                addStr = GetString();
                if (t.ToLower() == "t" || t.ToLower() == "f")
                {
                    k += t;
                    k += addStr;
                    bool b = k.ToLower() == "true" ? true : false;
                    jd.SetValue(b);
                }
                else if (t.ToLower() == "n")
                {
                    k += t;
                    k += addStr;
                    return null;
                }
                else
                {
                    k += t;
                    k += addStr;
                    if (k.ToLower() == "null")
                    {
                        return null;
                    }
                    if (k == "}" || k == "]")
                    {
                        curPos -= 1;
                        return null;
                    }
                    jd.SetValue(double.Parse(k.Trim()));
                }
            }
            return jd;
        }

        private string GetStringValue()
        {
            string k = "";
            token = Read();
            while (token != "\"")
            {
                k += token;
                token = Read();
            }
            return k;
        }

        private string GetString()
        {
            string k = "";
            token = Read();
            while (token != "\"" && token != "," && token != "}" && token != "]" && !string.IsNullOrEmpty(token))
            {
                k += token;
                token = Read();
            }
            if (token == "}" || token == "]")
            {
                curPos -= 1;
            }
            return k;
        }

        private string Read()
        {
            if (curPos >= len)
            {
                return "";
            }
            string s = orgStr.Substring(curPos, 1);
            curPos++;
            while (s == "\n" || s == "\r")
            {
                s = orgStr.Substring(curPos, 1);
                curPos++;
            }

            return s;
        }

        private string ReadUnSpace()
        {
            if (curPos >= len)
            {
                return "";
            }
            string s = orgStr.Substring(curPos, 1);
            curPos++;
            while (s == "\n" || s == "\r" || s == " ")
            {
                s = orgStr.Substring(curPos, 1);
                curPos++;
            }

            return s;
        }
    }
}

JsonTools.cs:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace AzhaoJson
{
    public class JsonTools
    {
        /// <summary>
        /// 通过正常类型获取自定义类型的枚举
        /// </summary>
        /// <param name="type">对象实际类型</param>
        /// <returns></returns>
        static public string GetDataType(Type type)
        {
            if (type == typeof(int) || type == typeof(float) || type == typeof(double) || type == typeof(Single) || type == typeof(long))
            {
                return DataType.NUMBER;
            }
            else if (type == typeof(string))
            {
                return DataType.STRING;
            }
            else if (type == typeof(bool))
            {
                return DataType.BOOL;
            }
            else if (type.IsGenericType)
            {
                if (type.GetGenericTypeDefinition() == typeof(Dictionary<,>))
                {
                    return DataType.DICTIONARY;
                }
                else
                {
                    return DataType.ARRAY;
                }                    
            }
            else if (type.BaseType == typeof(Array))
            {
                return DataType.ARRAY;
            }
            else if(type.IsClass)
            {
                return DataType.OBJECT;
            }
            else
            {
                FieldInfo[] fields = type.GetFields();
                if(fields!=null&&fields.Length>0)
                {
                    return DataType.OBJECT;
                }
                else
                {
                    return DataType.OTHER;
                }
            }
        }
        #region 对象转字符串
        /// <summary>
        /// 对字符串做trim和移除换行符
        /// </summary>
        /// <param name="str">需要转换的字符串</param>
        /// <returns></returns>
        static public string TrimStr(string str)
        {
            str = str.Replace("\r", "");
            str = str.Replace("\n", "");
            str = str.Replace("\t", "");
            str = str.Trim();
            return str;
        }

        /// <summary>
        /// 对象转字符串
        /// </summary>
        /// <param name="obj">需要转换的对象</param>
        /// <returns></returns>
        static public string GetObjectString(object obj)
        {
            string str = "";
            Type type = obj.GetType();
            string dataType = JsonTools.GetDataType(type);
            if (dataType == DataType.NUMBER)
            {
                str = obj.ToString();
            }
            else if (dataType == DataType.STRING)
            {
                str += "\"";
                str += obj.ToString();
                str += "\"";
            }
            else if (dataType == DataType.BOOL)
            {
                str = obj.ToString().ToLower();
            }
            else if (dataType == DataType.DICTIONARY)
            {
                str = GetDictStr(obj);
            }
            else if (dataType == DataType.ARRAY)
            {
                str = GetArrayTypeString(obj);
            }
            else if (dataType == DataType.OBJECT)
            {
                str += "{";

                FieldInfo[] fields = type.GetFields();
                for (int i = 0; i < fields.Length; i++)
                {
                    if (!fields[i].IsPublic)
                    {
                        continue;
                    }
                    if (fields[i].IsStatic)
                    {
                        continue;
                    }
                    str += "\"";
                    str += fields[i].Name;
                    str += "\":";
                    object value = fields[i].GetValue(obj);
                    if (value != null)
                    {
                        str += GetObjectString(value);
                    }
                    else
                    {
                        str += "null";
                    }
                    if (i < fields.Length - 1)
                    {
                        str += ",";
                    }

                }
                str += "}";
            }
            else
            {
                FieldInfo[] fields = type.GetFields();
                if (fields != null && fields.Length > 0)
                {
                    str += "{";
                    for (int i = 0; i < fields.Length; i++)
                    {
                        str += "\"";
                        str += fields[i].Name;
                        str += "\":";
                        object value = fields[i].GetValue(obj);
                        if (value != null)
                        {
                            str += GetObjectString(value);
                        }
                        else
                        {
                            str += "null";
                        }
                        if (i < fields.Length - 1)
                        {
                            str += ",";
                        }

                    }
                    str += "}";

                }
            }
            return str;

        }
        /// <summary>
        /// Dictionary转字符串
        /// </summary>
        /// <param name="dict">Dictionary对象</param>
        /// <returns></returns>
        public static string GetDictStr(object dict)
        {
            string str = "";
            str += "{";
            IEnumerable en = dict as IEnumerable;
            int ind = 0;
            int len = 0;
            foreach (object obj in en)
            {
                len++;
            }
            foreach (object obj in en)
            {
                PropertyInfo[] fields = obj.GetType().GetProperties();
                object k = null;
                object v = null;
                for (int i = 0; i < fields.Length; i++)
                {
                    string n = fields[i].Name;
                    object subObj = fields[i].GetValue(obj, null);
                    if (n.ToLower() == "key")
                    {
                        k = subObj;
                    }
                    else if (n.ToLower() == "value")
                    {
                        v = subObj;
                    }
                }
                if (k != null && v != null)
                {
                    str += GetObjectString(k);
                    str += ":";
                    str += GetObjectString(v);
                    if (ind < len - 1)
                    {
                        str += ",";
                    }
                }
                ind++;

            }
            str += "}";
            return str;
        }
        /// <summary>
        /// 数组转字符串,可以是Array或者List
        /// </summary>
        /// <param name="arrayObj">数组对象</param>
        /// <returns></returns>
        static public string GetArrayTypeString(object arrayObj)
        {
            string str = "";
            str += "[";
            Type type = arrayObj.GetType();
            if (type.IsGenericType)
            {
                str += GetListString(arrayObj);
            }
            if (type.BaseType == typeof(Array))
            {
                str += GetArrayString(arrayObj);
            }
            str += "]";
            return str;
        }
        /// <summary>
        /// List转字符串
        /// </summary>
        /// <param name="listObj">list对象</param>
        /// <returns></returns>
        static public string GetListString(object listObj)
        {
            string str = "";
            IEnumerable en = listObj as IEnumerable;
            List<object> list = new List<object>();
            foreach (object obj in en)
            {
                list.Add(obj);
            }
            for (int i = 0; i < list.Count; i++)
            {
                str += GetObjectString(list[i]);
                if (i < list.Count - 1)
                {
                    str += ",";
                }
            }
            return str;
        }
        /// <summary>
        /// Array转字符串
        /// </summary>
        /// <param name="arrayObj">array对象</param>
        /// <returns></returns>
        static private string GetArrayString(object arrayObj)
        {
            string str = "";
            Array orgarr = arrayObj as Array;
            object[] arr = new object[orgarr.Length];
            orgarr.CopyTo(arr, 0);
            for (int i = 0; i < arr.Length; i++)
            {
                str += GetObjectString(arr[i]);
                if (i < arr.Length - 1)
                {
                    str += ",";
                }
            }
            return str;
        }
        /// <summary>
        /// JsonData对象转字符串
        /// </summary>
        /// <param name="jd">JsonData对象</param>
        /// <returns></returns>
        static public string GetStringByJD(JsonData jd)
        {
            string str = "";

            string dataType = jd.Type;
            if (dataType == DataType.NUMBER)
            {
                str = jd.ToString();
            }
            else if (dataType == DataType.STRING)
            {
                str += "\"";
                str += jd.ToString();
                str += "\"";
            }
            else if (dataType == DataType.BOOL)
            {
                str = jd.ToString().ToLower();
            }
            else if (dataType == DataType.ARRAY)
            {
                str = GetArrayStrByJD(jd);
            }
            else if (dataType == DataType.OBJECT)
            {
                str += "{";

                List<string> keys = jd.GetKeys();
                if (keys == null)
                {
                    return "";
                }
                for (int i = 0; i < keys.Count; i++)
                {
                    str += "\"";
                    str += keys[i];
                    str += "\":";
                    JsonData value = jd.Get(keys[i]);
                    if (value != null)
                    {
                        str += GetStringByJD(value);
                    }
                    else
                    {
                        str += "null";
                    }
                    if (i < keys.Count - 1)
                    {
                        str += ",";
                    }

                }
                str += "}";
            }
            return str;
        }
        /// <summary>
        /// 通过JsonData获得数组字符串
        /// </summary>
        /// <param name="jd">JsonData对象</param>
        /// <returns></returns>
        static public string GetArrayStrByJD(JsonData jd)
        {
            string str = "";
            str += "[";
            str += GetListStrByJd(jd);

            str += "]";
            return str;
        }
        /// <summary>
        /// 通过JsonData单纯转换数组本身的字符串
        /// </summary>
        /// <param name="jd">JsonData对象</param>
        /// <returns></returns>
        static public string GetListStrByJd(JsonData jd)
        {
            string str = "";

            List<JsonData> list = jd.GetList();
            if (list == null)
            {
                return "";
            }
            for (int i = 0; i < list.Count; i++)
            {
                str += GetStringByJD(list[i]);
                if (i < list.Count - 1)
                {
                    str += ",";
                }
            }
            return str;
        }
        #endregion

        #region JsonData转对象
        /// <summary>
        /// JsonData转对象
        /// </summary>
        /// <param name="type">需要转换的类型</param>
        /// <param name="jd">JsonData对象</param>
        /// <returns></returns>
        static public object GetObjectByType(Type type, JsonData jd)
        {
            string realType = JsonTools.GetDataType(type);
            if (realType == DataType.OBJECT)
            {
                return GetObjectByObjectType(type, jd);
            }
            else if (realType == DataType.ARRAY)
            {
                if (type.IsGenericType)
                {
                    Type listType = type.GetMethod("Find").ReturnType;
                    object orgList = Activator.CreateInstance(type);

                    for (int j = 0; j < jd.Count; j++)
                    {
                        object lo = GetObjectByType(listType, jd.Get(j));
                        if (lo != null)
                        {
                            MethodInfo m = orgList.GetType().GetMethod("Add");
                            m.Invoke(orgList, new object[] { lo });
                        }
                    }

                    return orgList;

                }
                else if (type.BaseType == typeof(Array))
                {
                    MethodInfo[] ms = type.GetMethods();
                    Type listType = type.GetElementType();
                    object orgList = Array.CreateInstance(listType, jd.Count);
                    MethodInfo sv = type.GetMethod("SetValue", new Type[2] { typeof(object), typeof(int) });
                    for (int j = 0; j < jd.Count; j++)
                    {
                        object lo = GetObjectByType(listType, jd.Get(j));
                        if (lo != null)
                        {
                            sv.Invoke(orgList, new object[] { lo, j });
                        }
                    }

                    return orgList;
                }
            }
            else if (realType == DataType.BOOL)
            {
                bool bv = jd.ToString().ToLower() == "true" ? true : false;
                return bv;
            }
            else if (realType == DataType.STRING)
            {
                return jd.ToString();
            }
            else if (realType == DataType.NUMBER)
            {
                string sv = jd.ToString();
                if (type == typeof(int))
                {
                    return int.Parse(sv);
                }
                else if (type == typeof(float))
                {
                    double dsv = Convert.ToDouble(sv);
                    float fsv = Convert.ToSingle(dsv);
                    return fsv;
                }
                else if (type == typeof(double))
                {
                    return double.Parse(sv);
                }
                else if (type == typeof(Single))
                {
                    return Single.Parse(sv);
                }
                else if (type == typeof(long))
                {
                    return long.Parse(sv);
                }
            }
            else if (realType == DataType.DICTIONARY)
            {
                object orgList = Activator.CreateInstance(type);

                Type type1 = type.GetGenericArguments()[0];
                Type type2 = type.GetGenericArguments()[1];
                MethodInfo add = type.GetMethod("Add", new Type[2] { type1, type2 });
                MethodInfo m = orgList.GetType().GetMethod("Add");
                Dictionary<object, JsonData> dict = jd.GetObjDict();
                if (dict != null && dict.Count > 0)
                {
                    foreach (KeyValuePair<object, JsonData> item in dict)
                    {
                        object lo = GetObjectByType(type2, item.Value);
                        Type keyType = item.Key.GetType();
                        object keyObj;
                        if (keyType != type1)
                        {
                            if (type1 == typeof(int))
                            {
                                keyObj = int.Parse(item.Key.ToString());
                            }
                            else if (type1 == typeof(float))
                            {
                                keyObj = float.Parse(item.Key.ToString());
                            }
                            else if (type1 == typeof(double))
                            {
                                keyObj = double.Parse(item.Key.ToString());
                            }
                            else if (type1 == typeof(string))
                            {
                                keyObj = item.Key.ToString();
                            }
                            else
                            {
                                keyObj = item.Key.ToString();
                            }
                        }
                        else
                        {
                            keyObj = item.Key;
                        }
                        if (lo != null)
                        {
                            m.Invoke(orgList, new object[] { keyObj, lo });
                        }
                    }
                    return orgList;
                }
                else
                {
                    return null;
                }
            }

            return null;

        }
        /// <summary>
        /// JsonData转结构体对象
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="jd">JsonData对象</param>
        /// <returns></returns>
        static public object GetObjectByObjectType(Type type, JsonData jd)
        {
            FieldInfo[] fields = type.GetFields();
            if (fields.Length == 0)
            {
                return null;
            }
            object objT = (object)Activator.CreateInstance(type);

            for (int i = 0; i < fields.Length; i++)
            {
                if (!fields[i].IsPublic)
                {
                    continue;
                }
                if (fields[i].IsStatic)
                {
                    continue;
                }
                string fieldName = fields[i].Name;
                JsonData subJd = jd.Get(fieldName);
                if (subJd == null)
                {
                    continue;
                }
                Type subType = fields[i].FieldType;
                string realType = JsonTools.GetDataType(subType);
                if (realType == DataType.OBJECT)
                {
                    object subObj = GetObjectByType(subType, subJd);
                    fields[i].SetValue(objT, subObj);
                }
                else if (realType == DataType.ARRAY)
                {
                    if (subType.IsGenericType)
                    {
                        Type listType = subType.GetMethod("Find").ReturnType;
                        object orgList = Activator.CreateInstance(subType);

                        for (int j = 0; j < subJd.Count; j++)
                        {
                            object lo = GetObjectByType(listType, subJd.Get(j));
                            if (lo != null)
                            {
                                MethodInfo m = orgList.GetType().GetMethod("Add");
                                m.Invoke(orgList, new object[] { lo });
                            }
                        }

                        fields[i].SetValue(objT, orgList);

                    }
                    else if (subType.BaseType == typeof(Array))
                    {
                        MethodInfo[] ms = subType.GetMethods();
                        Type listType = subType.GetElementType();
                        object orgList = Array.CreateInstance(listType, subJd.Count);
                        MethodInfo sv = subType.GetMethod("SetValue", new Type[2] { typeof(object), typeof(int) });
                        for (int j = 0; j < subJd.Count; j++)
                        {
                            object lo = GetObjectByType(listType, subJd.Get(j));
                            if (lo != null)
                            {
                                sv.Invoke(orgList, new object[] { lo, j });
                            }
                        }

                        fields[i].SetValue(objT, orgList);
                    }
                }
                else if (realType == DataType.BOOL)
                {
                    bool bv = subJd.ToString().ToLower() == "true" ? true : false;
                    fields[i].SetValue(objT, bv);
                }
                else if (realType == DataType.STRING)
                {
                    fields[i].SetValue(objT, subJd.ToString());
                }
                else if (realType == DataType.NUMBER)
                {
                    string sv = subJd.ToString();
                    if (subType == typeof(int))
                    {
                        fields[i].SetValue(objT, int.Parse(sv));
                    }
                    else if (subType == typeof(float))
                    {
                        double dsv = Convert.ToDouble(sv);
                        float fsv = Convert.ToSingle(dsv);
                        fields[i].SetValue(objT, fsv);
                    }
                    else if (subType == typeof(double))
                    {
                        fields[i].SetValue(objT, double.Parse(sv));
                    }
                    else if (subType == typeof(Single))
                    {
                        fields[i].SetValue(objT, Single.Parse(sv));
                    }
                    else if (subType == typeof(long))
                    {
                        fields[i].SetValue(objT, long.Parse(sv));
                    }
                }
                else if (realType == DataType.DICTIONARY)
                {
                    object orgList = Activator.CreateInstance(subType);
                    Type type1 = subType.GetGenericArguments()[0];
                    Type type2 = subType.GetGenericArguments()[1];
                    MethodInfo add = subType.GetMethod("Add", new Type[2] { type1, type2 });
                    MethodInfo m = orgList.GetType().GetMethod("Add");
                    Dictionary<object, JsonData> dict = subJd.GetObjDict();
                    if (dict != null && dict.Count > 0)
                    {
                        foreach (KeyValuePair<object, JsonData> item in dict)
                        {
                            object lo = GetObjectByType(type2, item.Value);
                            Type keyType = item.Key.GetType();
                            object keyObj;
                            if (keyType != type1)
                            {
                                if (type1 == typeof(int))
                                {
                                    keyObj = int.Parse(item.Key.ToString());
                                }
                                else if (type1 == typeof(float))
                                {
                                    keyObj = float.Parse(item.Key.ToString());
                                }
                                else if (type1 == typeof(double))
                                {
                                    keyObj = double.Parse(item.Key.ToString());
                                }
                                else if (type1 == typeof(string))
                                {
                                    keyObj = item.Key.ToString();
                                }
                                else
                                {
                                    keyObj = item.Key.ToString();
                                }
                            }
                            else
                            {
                                keyObj = item.Key;
                            }
                            if (lo != null)
                            {
                                m.Invoke(orgList, new object[] { keyObj, lo });
                            }
                        }
                        fields[i].SetValue(objT, orgList);

                    }
                }

            }
            return objT;
        }
        #endregion
    }
}
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值