jackson操作对象json互转

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.2.3</version>
</dependency>
<dependency>
	<groupId>org.codehaus.jackson</groupId>
	<artifactId>jackson-mapper-asl</artifactId>
	<version>1.8.5</version>
</dependency>
public class TestMain {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        List<Role> listRole = new ArrayList<Role>();
        
        Role role1 = new Role();
        role1.setRoleType("admin");
        role1.setLoginTime("2015-12-7");
        Role role2 = new Role();
        role2.setRoleType("test");
        role2.setLoginTime("2015-12-8");
        listRole.add(role1);
        listRole.add(role2);
        User user = new User();
        user.setName("abstract");
        user.setPass("password");
        user.setRole(listRole);
        
        // 拼装
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(user);
        System.out.println(json);
        
        // 解析
        JsonNode node = mapper.readTree(json);
        System.out.println("name: " + node.path("name").asText());
        JsonNode roleNode = node.path("role");
        for(int i=0;i<roleNode.size();i++){
            System.out.println("roleType: " + mapper.readTree(roleNode.get(i).toString()).path("roleType").asText());
        }
    }

}

class User{
    private String name;
    private String pass;
    private List<Role> role;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPass() {
        return pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }
    public List<Role> getRole() {
        return role;
    }
    public void setRole(List<Role> role) {
        this.role = role;
    }
    
}

class Role{
    private String roleType;
    private String loginTime;
    public String getRoleType() {
        return roleType;
    }
    public void setRoleType(String roleType) {
        this.roleType = roleType;
    }
    public String getLoginTime() {
        return loginTime;
    }
    public void setLoginTime(String loginTime) {
        this.loginTime = loginTime;
    }
}

输出为:

{"name":"abstract","pass":"password","role":[{"roleType":"admin","loginTime":"2015-12-7"},{"roleType":"test","loginTime":"2015-12-8"}]}
name: abstract
roleType: admin
roleType: test

 

还有很多功能,比如忽略null等,指定哪些属性不显示等具体参考官方api http://wiki.fasterxml.com/JacksonJavaDocs

你可能感兴趣的:(json解析,Jackson,json串儿,json拼装与解析,json拼装)