日期:2014-05-16  浏览次数:20400 次

Jackson学习一之对象与JSON互相转化

简介:

Jackson是一个流行的基于Java的JSON处理框架

官方wiki:http://wiki.fasterxml.com/JacksonInFiveMinutes

官方文档:http://wiki.fasterxml.com/JacksonDocumentation

学习参考:?Json转换利器Gson之实例?系列,顺便也学习一下GSON

?

本篇简介如何使用Jackson进行Java对象与JSON的互相转换

新建基本Student类:

package com.jingshou.pojo;

import java.util.Date;

public class Student {
	private int id;
	private String name;
	private Date birthDay;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public Date getBirthDay() {
		return birthDay;
	}

	public void setBirthDay(Date birthDay) {
		this.birthDay = birthDay;
	}

	@Override
	public String toString() {
		return "Student [birthDay=" + birthDay + ", id=" + id + ", name="
				+ name + "]";
	}

}

?班级类:

package com.jingshou.pojo;

import java.util.List;

public class Class {
	private String cname;
	private List<Student> members;
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}
	public List<Student> getMembers() {
		return members;
	}
	public void setMembers(List<Student> members) {
		this.members = members;
	}
	
	public String toString(){
		return "The Class Name is: " + cname + " " + "The members are: " + members;
		
	}
	

}

?

测试代码:

package com.jingshou.jackson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jingshou.pojo.Class;
import com.jingshou.pojo.Student;

public class JacksonTest1 {

	public static void main(String[] args) throws IOException {
		Student student1 = new Student();  
		student1.setId(5237);
		student1.setName("jingshou");
		student1.setBirthDay(new Date());
		
        ObjectMapper mapper = new ObjectMapper();
        
        // Convert object to JSON string
        String Json =  mapper.writeValueAsString(student1);
        System.out.println("Change Object to JSON String: " + Json);
        
        // Convert Json string to Object
        Student student2 = mapper.readValue(Json, Student.class);
        System.out.println(student2);
        
        // Create a student list add it to Bj
        Student student3 = new Student();  
        student3.setId(5117);  
        student3.setName("saiya");  
        student3.setBirthDay(new Date());  
  
        List<Student> stuList = new ArrayList<Student>();
        stuList.add(student1);
        stuList.add(student3);
        
        Class bj = new Class();
        bj.setCname("五年二班");
        bj.setMembers(stuList);
        
        String json2 = mapper.writeValueAsString(bj);
        System.out.println("The JSON from Class is: " + json2);
        
        Class bj2 = mapper.readValue(json2, Class.class);
        System.out.println(bj2);
        

	}

}

?运行结果:

Change Object to JSON String: {"id":5237,"name":"jingshou"