Home > Backend Development > C#.Net Tutorial > Customized method to convert Json string to C# object

Customized method to convert Json string to C# object

高洛峰
Release: 2017-01-18 09:56:22
Original
1254 people have browsed it

Atrribute is used here to convert Json strings into C# objects. Due to functional limitations, this version is only for Json strings, such as "response":"Hello","id":21231513,"result":100,"msg":"OK."; rather than Json arrays. The Atrribute here acts on the attribute. Like the Atrribute in NHibernate, it uses reflection at runtime to obtain which key in the Json string this attribute corresponds to.

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; }
        }
    }
}
Copy after login

The next step is the conversion tool The core code mainly decomposes and analyzes the key and value in the Json string, and obtains and assigns each corresponding attribute in the object through reflection.

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 });
        }
    }
}
Copy after login

Finally this is the code for testing

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; }
    }
Copy after login
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);
        }
    }
Copy after login

For more customized methods to convert Json strings into C# objects, please pay attention to the PHP Chinese website for related articles!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template