国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

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

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

這里使用Atrribute的方式實(shí)現(xiàn)了Json字符串向C#對象的轉(zhuǎn)變。因?yàn)楣δ芫窒蓿税姹局皇轻槍τ贘son字符串,如"response":"Hello","id":21231513,"result":100,"msg":"OK."; 而不是Json數(shù)組。這里的Atrribute是作用在屬性上,像NHibernate中的Atrribute一樣,是在運(yùn)行時(shí)通過反射來獲取這個(gè)屬性對應(yīng)于Json字符串中的哪個(gè)key.

復(fù)制代碼 代碼如下:

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; }
        }
    }
}


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

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 });
        }
    }
}

最后這是用于測試的代碼

復(fù)制代碼 代碼如下:

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; }
    }

復(fù)制代碼 代碼如下:

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ā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 洞口县| 乌拉特前旗| 永丰县| 二连浩特市| 儋州市| 资中县| 鄂托克旗| 枞阳县| 泗阳县| 虎林市| 高邑县| 民勤县| 景泰县| 保德县| 呼伦贝尔市| 福贡县| 虞城县| 山阴县| 金秀| 白城市| 满洲里市| 金溪县| 伽师县| 盐城市| 方正县| 湛江市| 千阳县| 贡山| 石景山区| 泗阳县| 册亨县| 正安县| 增城市| 鹰潭市| 高淳县| 苍溪县| 乐平市| 平塘县| 眉山市| 隆回县| 乌鲁木齐县|