Jackson处理复杂对象类型


一.Jackson处理复杂类型(List,map)两种方法

方法一:

String jsonString="[{'id':'1'},{'id':'2'}]";  
ObjectMapper mapper = new ObjectMapper();  
JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Bean.class);  
//如果是Map类型  mapper.getTypeFactory().constructParametricType(HashMap.class,String.class, Bean.class);  
List<Bean> lst =  (List<Bean>)mapper.readValue(jsonString, javaType);

方法二:

String jsonString="[{'id':'1'},{'id':'2'}]";  
ObjectMapper mapper = new ObjectMapper();  
List<Bean> beanList = mapper.readValue(jsonString, new TypeReference<List<Bean>>() {}); 

 

二.jackson复杂对象集合的几种简单转换

Role.java

package com.bijian.test;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Role {

    @JsonProperty(value = "Roleid")
    private int roleid;
    
    @JsonProperty(value = "Name")
    private String name;
    
    @JsonProperty(value = "Show_Name")
    private String show_name;
    
    @JsonProperty(value = "Remark")
    private String remark;
    
    @JsonProperty(value = "Type")
    private String type;

    public int getRoleid() {
        return roleid;
    }

    public void setRoleid(int roleid) {
        this.roleid = roleid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getShow_name() {
        return show_name;
    }

    public void setShow_name(String show_name) {
        this.show_name = show_name;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

User.java

package com.bijian.test;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    
    @JsonProperty(value = "UserID")
    private int userId;
    
    @JsonProperty(value = "LoginName")
    private String loginName;
    
    @JsonProperty(value = "Truename")
    private String truename;
    
    @JsonProperty(value = "Nickname")
    private String nickname;
    
    @JsonProperty(value = "LoginPwd")
    private String loginPwd;
    
    @JsonProperty(value = "QQ")
    private String qq;
    
    @JsonProperty(value = "Phone")
    private String phone;
    
    @JsonProperty(value = "Email")
    private String email;
    
    @JsonProperty(value = "Remark")
    private String remark;
    
    @JsonProperty(value = "Account_Non_Locked")
    private String account_non_locked;
    
    @JsonProperty(value = "Telelephone")
    private String telelephone;
    
    @JsonProperty(value = "IsDelete")
    private int isDelete;
    
    @JsonProperty(value = "RoleList")
    private List<Role> roleList;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getLoginName() {
        return loginName;
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }

    public String getTruename() {
        return truename;
    }

    public void setTruename(String truename) {
        this.truename = truename;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getLoginPwd() {
        return loginPwd;
    }

    public void setLoginPwd(String loginPwd) {
        this.loginPwd = loginPwd;
    }

    public String getQq() {
        return qq;
    }

    public void setQq(String qq) {
        this.qq = qq;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getAccount_non_locked() {
        return account_non_locked;
    }

    public void setAccount_non_locked(String account_non_locked) {
        this.account_non_locked = account_non_locked;
    }

    public String getTelelephone() {
        return telelephone;
    }

    public void setTelelephone(String telelephone) {
        this.telelephone = telelephone;
    }

    public int getIsDelete() {
        return isDelete;
    }

    public void setIsDelete(int isDelete) {
        this.isDelete = isDelete;
    }

    public List<Role> getRoleList() {
        return roleList;
    }

    public void setRoleList(List<Role> roleList) {
        this.roleList = roleList;
    }
}

Main.java

package com.bijian.test;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * jackson 复杂对象集合 的几种简单转换
 */
public class Main<T> {
    static ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

        String josn = "{\"UserID\":1,\"LoginName\":\"唐工\",\"Truename\":\"超级\",\"Nickname\":null,\"LoginPwd\":\"E10ADC3949BA59ABBE56E057F20F883E\",\"QQ\":\"\",\"Phone\":\"\",\"Email\":null,\"Remark\":\"\",\"Account_Non_Locked\":0,\"Telelephone\":null,\"IsDelete\":0}";
        User u = mapper.readValue(josn, User.class);
        // User u=new Main<User>().jsonStreamConverObject(josn, User.class);
        System.out.println("转对象:" + u);

        // 转集合
        String josn2 = "[{\"UserID\":1,\"LoginName\":\"唐工\",\"Truename\":\"超级\",\"Nickname\":null,\"LoginPwd\":\"E10ADC3949BA59ABBE56E057F20F883E\",\"QQ\":\"\",\"Phone\":\"\",\"Email\":null,\"Remark\":\"\",\"Account_Non_Locked\":0,\"Telelephone\":null,\"IsDelete\":0}]";
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, User.class);
        List<User> me = mapper.readValue(josn2, javaType);
        System.out.println("转集合me:" + me);

        // 对象里有 集合 转换
        String josn3 = "{\"UserID\":1,\"LoginName\":\"唐工\",\"Truename\":\"超级\",\"Nickname\":null,\"LoginPwd\":\"E10ADC3949BA59ABBE56E057F20F883E\",\"QQ\":\"\",\"Phone\":\"\",\"Email\":null,\"Remark\":\"\",\"Account_Non_Locked\":0,\"Telelephone\":null,\"IsDelete\":0,\"RoleList\":[{\"Name\":\"超级管理员\",\"Roleid\":0,\"Show_Name\":\"超级管理员\",\"Remark\":null,\"Type\":1}]}";

//        User u3 = JsonUtil.fromJson(josn3, User.class);
        User u3 = mapper.readValue(josn3, User.class); // 简单方式
        // User u3=new Main<User>().jsonConverObject(josn3, User.class); 流方式
        System.out.println("转对象里有集合u3:" + u3);
        System.out.println("转对象里有集合u3.getRoleList().size():" + u3.getRoleList().size());

        // 集合 对象 集合 转换
        String josn4 = "[{\"UserID\":1,\"LoginName\":\"唐工\",\"Truename\":\"超级\",\"Nickname\":null,\"LoginPwd\":\"E10ADC3949BA59ABBE56E057F20F883E\",\"QQ\":\"\",\"Phone\":\"\",\"Email\":null,\"Remark\":\"\",\"Account_Non_Locked\":0,\"Telelephone\":null,\"IsDelete\":0,\"RoleList\":[{\"Roleid\":0,\"Name\":\"超级管理员\",\"Show_Name\":\"超级管理员\",\"Remark\":null,\"Type\":1}]},{\"UserID\":2,\"LoginName\":\"唐工\",\"Truename\":\"超级\",\"Nickname\":null,\"LoginPwd\":\"E10ADC3949BA59ABBE56E057F20F883E\",\"QQ\":\"\",\"Phone\":\"\",\"Email\":null,\"Remark\":\"\",\"Account_Non_Locked\":0,\"Telelephone\":null,\"IsDelete\":0,\"RoleList\":[{\"Roleid\":0,\"Name\":\"超级管理员\",\"Show_Name\":\"超级管理员\",\"Remark\":null,\"Type\":1}]}]";
        JavaType javaType4 = mapper.getTypeFactory().constructParametricType(List.class, User.class);
        List<User> list = mapper.readValue(josn4, javaType4);
        System.out.println("集合里是对象 对象里有集合转换:" + list);
    }

    /***
     * 转对象
     * @param josn
     * @param clz
     * @return
     */
    public T jsonStreamConverObject(String josn, Class<T> clz) {

        T t = null;
        // ObjectMapper jacksonMapper = new ObjectMapper();
        InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(josn.getBytes()));
        BufferedReader streamReader = new BufferedReader(in);
        StringBuilder buff = new StringBuilder();
        String inputStr;
        try {
            while ((inputStr = streamReader.readLine()) != null)
                buff.append(inputStr);
            // ObjectMapper mapper = new ObjectMapper();
            t = mapper.readValue(buff.toString(), clz);

        } catch (IOException e) {

            e.printStackTrace();
        }

        return t;
    }

    /***
     * 转对象
     * @param josn
     * @param clz
     * @return
     */
    public T jsonConverObject(String josn, Class<T> clz) {

        T t = null;
        try {
            t = mapper.readValue(josn, clz);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return t;
    }

    /**
     * 转集合
     * @param josn
     * @param clz
     * @return
     */
    public List<T> jsonConverList(String josn, Class<T> clz) {

        List<T> me = null;
        try {
            // jacksonMapper
            // .disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
            // jacksonMapper.enableDefaultTyping();
            // jacksonMapper.setVisibility(JsonMethod.FIELD,JsonAutoDetect.Visibility.ANY);
            // jacksonMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT,
            // false);//格式化
            // jacksonMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
            // jacksonMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,
            // false);

            JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, clz);// clz.selGenType().getClass()

            me = mapper.readValue(josn, javaType);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return me;
    }
}

/**
 * output:
 * 转对象:User [UserID=1, LoginName=唐工, Truename=超级, Nickname=null, LoginPwd=E10ADC3949BA59ABBE56E057F20F883E, QQ=, Phone=, Email=null, Remark=, Account_Non_Locked=0, Telelephone=null, Indate=null, IsDelete=0, RoleList=null]
 * 转集合me:[User [UserID=1, LoginName=唐工, Truename=超级, Nickname=null, LoginPwd=E10ADC3949BA59ABBE56E057F20F883E, QQ=, Phone=, Email=null, Remark=, Account_Non_Locked=0, Telelephone=null, Indate=null, IsDelete=0, RoleList=null]]
 * 转对象里有集合u3:User [UserID=1, LoginName=唐工, Truename=超级, Nickname=null, LoginPwd=E10ADC3949BA59ABBE56E057F20F883E, QQ=, Phone=, Email=null, Remark=, Account_Non_Locked=0, Telelephone=null, Indate=null, IsDelete=0, RoleList=[Role [Roleid=0, Name=超级管理员, Show_Name=超级管理员, Remark=null, Type=1]]]
 * 集合里是对象 对象里有集合转换:[User [UserID=1, LoginName=唐工, Truename=超级, Nickname=null, LoginPwd=E10ADC3949BA59ABBE56E057F20F883E, QQ=, Phone=, Email=null, Remark=, Account_Non_Locked=0, Telelephone=null, Indate=null, IsDelete=0, RoleList=[Role [Roleid=0, Name=超级管理员, Show_Name=超级管理员, Remark=null, Type=1]]], User [UserID=2, LoginName=唐工, Truename=超级, Nickname=null, LoginPwd=E10ADC3949BA59ABBE56E057F20F883E, QQ=, Phone=, Email=null, Remark=, Account_Non_Locked=0, Telelephone=null, Indate=null, IsDelete=0, RoleList=[Role [Roleid=0, Name=超级管理员, Show_Name=超级管理员, Remark=null, Type=1]]]]

 * */

运行结果:

转对象:com.bijian.test.User@5e04d6b0
转集合me:[com.bijian.test.User@faaed09]
转对象里有集合u3:com.bijian.test.User@1eaff1e8
转对象里有集合u3.getRoleList().size():1
集合里是对象 对象里有集合转换:[com.bijian.test.User@3132c615, com.bijian.test.User@7c6aa5ee]

 

三.列表对象是一个内部类的转换

RspDTO.java

package com.bijian.test;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;

public class RspDTO {

    @JsonProperty(value = "OUTPUT")
    private Output output;
    
    @JsonProperty(value = "DETAIL")
    private List<Detail> detailList;

    public Output getOutput() {
        return output;
    }

    public void setOutput(Output output) {
        this.output = output;
    }

    public List<Detail> getDetailList() {
        return detailList;
    }

    public void setDetailList(List<Detail> detailList) {
        this.detailList = detailList;
    }

    public RspDTO() {
        super();
    }

    public RspDTO(Output output) {
        super();
        this.output = output;
    }

    public class Output {
        
        @JsonProperty(value = "NUMBER")
        private String number;

        @JsonProperty(value = "NAME")
        private String name;

        public String getNumber() {
            return number;
        }

        public void setNumber(String number) {
            this.number = number;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
    
    public class Detail {
        
        @JsonProperty(value = "NO")
        private Integer no;
        
        @JsonProperty(value = "STATUS")
        private String status;

        public Integer getNo() {
            return no;
        }

        public void setNo(Integer no) {
            this.no = no;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }
    }
}

Main2.java

package com.bijian.test;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main2 {

    static ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        
        String content = "{\"OUTPUT\":{\"NUMBER\":\"001\", \"NAME\":\"lisi\"}, \"DETAIL\":[{\"NO\":1, \"STATUS\":\"S\"}, {\"NO\":2, \"STATUS\":\"F\"}]}";
        RspDTO rspDTO = mapper.readValue(content, RspDTO.class); // 简单方式
        System.out.println("rspDTO:" + rspDTO);
        System.out.println("rspDTO detail:" + rspDTO.getDetailList());
    }
}

运行结果:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.bijian.test.RspDTO$Detail: can only instantiate non-static inner class by using default, no-argument constructor
 at [Source: {"OUTPUT":{"NUMBER":"001", "NAME":"lisi"}, "DETAIL":[{"NO":1, "STATUS":"S"}, {"NO":2, "STATUS":"F"}]}; line: 1, column: 55] (through reference chain: com.bijian.test.RspDTO["DETAIL"]->java.util.ArrayList[0])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)
    at com.fasterxml.jackson.databind.DeserializationContext.instantiationException(DeserializationContext.java:1456)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1012)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1203)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:314)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:287)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:259)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26)
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2858)
    at com.bijian.test.Main2.main(Main2.java:16)

        从报错堆栈来看,can only instantiate non-static inner class by using default。于是把Detail类改成静态的,如下所示:

package com.bijian.test;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;

public class RspDTO {

    @JsonProperty(value = "OUTPUT")
    private Output output;
    
    @JsonProperty(value = "DETAIL")
    private List<Detail> detailList;

    public Output getOutput() {
        return output;
    }

    public void setOutput(Output output) {
        this.output = output;
    }

    public List<Detail> getDetailList() {
        return detailList;
    }

    public void setDetailList(List<Detail> detailList) {
        this.detailList = detailList;
    }

    public RspDTO() {
        super();
    }

    public RspDTO(Output output) {
        super();
        this.output = output;
    }

    public class Output {
        
        @JsonProperty(value = "NUMBER")
        private String number;

        @JsonProperty(value = "NAME")
        private String name;

        public String getNumber() {
            return number;
        }

        public void setNumber(String number) {
            this.number = number;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
    
    public static class Detail {
        
        @JsonProperty(value = "NO")
        private Integer no;
        
        @JsonProperty(value = "STATUS")
        private String status;

        public Integer getNo() {
            return no;
        }

        public void setNo(Integer no) {
            this.no = no;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }
    }
}

运行结果正常,如下所示:

rspDTO:com.bijian.test.RspDTO@5a254de0
rspDTO detail:[com.bijian.test.RspDTO$Detail@471bdb5c, com.bijian.test.RspDTO$Detail@75de997c]

        这样看来,列表对象是一个内部类,这个内部类必须是static才能正常映射转换。

 

参考文章:http://blog.csdn.net/liangrui1988/article/details/43084993

http://blog.csdn.net/zhuyijian135757/article/details/38269715#


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM