自訂實作Json字串轉變為C#物件的方法

高洛峰
發布: 2017-01-18 09:56:22
原創
1180 人瀏覽過

這裡使用Atrribute的方式實現了Json字串向C#物件的轉變。因為功能限制,此版本只是針對Json字串,如"response":"Hello","id":21231513,"result":100,"msg":"OK."; 而不是Json陣列。這裡的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; }
        }
    }
}
登入後複製

接下來是這個轉換工具中的核心程式碼,主要是分解並且分析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(&#39;,&#39;);
            for (int i = 0; i < fields.Length; i++ )
            {
                string[] keyvalue = fields[i].Split(&#39;:&#39;);
                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);
        }
    }
登入後複製

更多自訂實現Json字串轉變為C#物件的方法相關文章請關注PHP中文網!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!