欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

自定义实现Json字符串向C#对象转变的方法

程序员文章站 2023-12-05 20:44:52
这里使用atrribute的方式实现了json字符串向c#对象的转变。因为功能局限,此版本只是针对于json字符串,如"response":"hello","id":212...

这里使用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(',');
            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);
        }
    }