a亚洲精品_精品国产91乱码一区二区三区_亚洲精品在线免费观看视频_欧美日韩亚洲国产综合_久久久久久久久久久成人_在线区

首頁 > 編程 > C# > 正文

自定義實現(xiàn)Json字符串向C#對象轉(zhuǎn)變的方法

2020-01-24 03:32:12
字體:
供稿:網(wǎng)友

這里使用Atrribute的方式實現(xiàn)了Json字符串向C#對象的轉(zhuǎn)變。因為功能局限,此版本只是針對于Json字符串,如"response":"Hello","id":21231513,"result":100,"msg":"OK."; 而不是Json數(shù)組。這里的Atrribute是作用在屬性上,像NHibernate中的Atrribute一樣,是在運行時通過反射來獲取這個屬性對應于Json字符串中的哪個key.

復制代碼 代碼如下:

namespace JsonMapper
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class JsonFieldAttribute : Attribute
    {
        private string _Name = string.Empty;

        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
    }
}


接下來是這個轉(zhuǎn)換工具中的核心代碼,主要是分解并且分析Json字符串中key與value, 并且通過反射獲得對象中的各個對應屬性并且賦值。
復制代碼 代碼如下:

namespace JsonMapper
{
    public class JsonToInstance
    {
        public T ToInstance<T>(string json) where T : new()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string[] fields = json.Split(',');
            for (int i = 0; i < fields.Length; i++ )
            {
                string[] keyvalue = fields[i].Split(':');
                dic.Add(Filter(keyvalue[0]), Filter(keyvalue[1]));
            }

            PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            T entity = new T();
            foreach (PropertyInfo property in properties)
            {
                object[] propertyAttrs = property.GetCustomAttributes(false);
                for (int i = 0; i < propertyAttrs.Length; i++)
                {
                    object propertyAttr = propertyAttrs[i];
                    if (propertyAttr is JsonFieldAttribute)
                    {
                        JsonFieldAttribute jsonFieldAttribute = propertyAttr as JsonFieldAttribute;
                        foreach (KeyValuePair<string ,string> item in dic)
                        {
                            if (item.Key == jsonFieldAttribute.Name)
                            {
                                Type t = property.PropertyType;
                                property.SetValue(entity, ToType(t, item.Value), null);
                                break;
                            }
                        }
                    }
                }
            }
            return entity;
        }

        private string Filter(string str)
        {
            if (!(str.StartsWith("/"") && str.EndsWith("/"")))
            {
                return str;
            }
            else
            {
                return str.Substring(1, str.Length - 2);
            }
        }

        public object ToType(Type type, string value)
        {
            if (type == typeof(string))
            {
                return value;
            }

            MethodInfo parseMethod = null;

            foreach (MethodInfo mi in type.GetMethods(BindingFlags.Static
                | BindingFlags.Public))
            {
                if (mi.Name == "Parse" && mi.GetParameters().Length == 1)
                {
                    parseMethod = mi;
                    break;
                }
            }

            if (parseMethod == null)
            {
                throw new ArgumentException(string.Format(
                    "Type: {0} has not Parse static method!", type));
            }

            return parseMethod.Invoke(null, new object[] { value });
        }
    }
}

最后這是用于測試的代碼

復制代碼 代碼如下:

public class Message
    {
        //{ "result": 100, "response": "Who are you?!", "id": 13185569, "msg": "OK." }

        [JsonField(Name = "result")]
        public int Result { get; set; }

        [JsonField(Name = "response")]
        public string Response { get; set; }

        [JsonField(Name = "id")]
        public int Id { get; set; }

        [JsonField(Name = "msg")]
        public string Msg { get; set; }
    }

復制代碼 代碼如下:

class Program
    {
        static void Main(string[] args)
        {
            JsonToInstance util = new JsonToInstance();
            string json = "/"response/":/"我是阿貓醬的小黃雞/",/"id/":21231513,/"result/":100,/"msg/":/"OK./"";
            Message m = util.ToInstance<Message>(json);
        }
    }

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 毛片黄片免费看 | 国产日韩中文字幕 | 一本色道精品久久一区二区三区 | av一区二区三区四区 | 麻豆专区一区二区三区四区五区 | 91日韩精品一区二区三区 | 男女免费在线观看 | 久久九| 精品欧美一区二区三区 | 亚洲男人天堂网 | 97精品在线视频 | 亚洲美女一区二区三区 | av在线免费观看一区二区 | 日韩av在线不卡 | 欧美在线免费观看 | 国产成人性色生活片 | 性高湖久久久久久久久 | 国产精品一级毛片在线 | 久久久久99| 日日爱夜夜爱 | 亚洲天堂影视 | 久久久久久99精品 | 亚洲电影一区二区 | 伊人午夜| 污网站免费在线 | 亚洲动漫在线观看 | 91小视频 | www..99热| 色婷婷综合久久久久中文一区二区 | 久久91| 成人免费观看在线视频 | 国产精品成人一区二区三区夜夜夜 | 亚洲精品久久久久久久久 | 国产乱精品一区二区三区 | 国产高潮好爽受不了了夜色 | 日韩精品一区二区三区第95 | 超碰在 | 91精品国产综合久久久久久 | 精品一区二区三区不卡 | 一区二区三区四区在线 | 一二区精品|