jackson操作对象json互转

阅读更多

	com.fasterxml.jackson.core
	jackson-databind
	2.2.3


	org.codehaus.jackson
	jackson-mapper-asl
	1.8.5
public class TestMain {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        List listRole = new ArrayList();
        
        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 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 getRole() {
        return role;
    }
    public void setRole(List 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

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