>  기사  >  백엔드 개발  >  Json 문자열을 C# 객체로 변환하는 사용자 정의 방법

Json 문자열을 C# 객체로 변환하는 사용자 정의 방법

高洛峰
高洛峰원래의
2017-01-18 09:56:221184검색

여기서 Atrribute는 Json 문자열을 C# 개체로 변환하는 데 사용됩니다. 기능 제한으로 인해 이 버전은 Json 배열이 아닌 "response":"Hello","id":21231513,"result":100,"msg":"OK.";와 같은 Json 문자열에만 사용됩니다. 여기서 Atrribute는 NHibernate의 Atrribute와 마찬가지로 런타임에 리플렉션을 사용하여 이 속성이 해당하는 Json 문자열의 키를 얻습니다.

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 문자열의 키와 값을 분석하고 리플렉션을 통해 객체의 해당 속성을 각각 획득하고 할당합니다.

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 중국어 웹사이트에서 관련 기사를 참고하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.