黎明前的黑暗
一切不行都是人不行

1、Maven依赖

       <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>net.sf.ezmorph</groupId>
            <artifactId>ezmorph</artifactId>
            <version>1.0.6</version>
        </dependency>

        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

 

2、方法实现

     /***
     * json字符串转java对象
     * @param t java对象
     * @param jsonStr json字符串
     * @param <T> 申明泛型
     * @return 返回泛型java对象
     */
    public static <T> T jsonToObject(T t, String jsonStr) {
        try {
            JsonConfig config = new JsonConfig();
            config.setRootClass(t.getClass());

            PropertyNameProcessor lowerCasePropertyNameProcessor = new PropertyNameProcessor() {
                @Override
                public String processPropertyName(Class aClass, String s) {
                    return s.substring(0, 1).toLowerCase() + s.substring(1);
                }
            };
            config.registerJavaPropertyNameProcessor(t.getClass(), lowerCasePropertyNameProcessor);

            //1、使用JSONObject
            JSONObject jsonObject = JSONObject.fromObject(jsonStr);
            T t1 = (T) JSONObject.toBean(jsonObject, config);
            return t1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

 

posted on 2019-05-16 14:00  无厘头的小情绪  阅读(257)  评论(0编辑  收藏  举报