jar包 jackson-annotations-2.2.3.jar jackson-core-2.2.3.jar jackson-databind-2.2.3.jar import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import itcast.domain.Person; public class test1 { @Test public void run1() throws Exception { Person p = new Person("张三", 23, "南通", new Date()); //创建jackson核心对象 ObjectMapper mapper = new ObjectMapper(); //调用方法将Java对象转为Json对象 String s = mapper.writeValueAsString(p); //将json写入文件中 mapper.writeValue(new File("D://a.txt"),p); //将数据写给客户端 //mapper.writeValue(response.getWriter(),p); System.out.println("s:" + s); } //复杂的数据格式(list) @Test public void run2() throws Exception { Person p = new Person("张三", 23, "南通", new Date()); Person p1 = new Person("李四", 24, "徐州", new Date()); Person p2 = new Person("王五", 25, "上海", new Date()); List<Person> list = new ArrayList<Person>(); list.add(p); list.add(p1); list.add(p2); //创建jackson核心对象 ObjectMapper mapper = new ObjectMapper(); //调用方法将Java对象转为Json对象 String s = mapper.writeValueAsString(list); System.out.println(s); } //复杂的数据格式(map) @Test public void run3() throws Exception { Map<String,Object> map = new HashMap<String,Object>(); map.put("name","张三"); map.put("age",23); map.put("address","南通"); //创建jackjson核心对象 ObjectMapper mapper = new ObjectMapper(); String s = mapper.writeValueAsString(map); System.out.println(s); } //json转java对象 @Test public void run4() throws Exception { String str="{\"address\":\"南通\",\"username\":\"张三\",\"age\":23}"; ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(str, Person.class); System.out.println(person); } }
//Java对象
public class Person { private String username; private int age; private String address; //忽略转化为json数据 //@JsonIgnore //类似于SimpleDateFormat @JsonFormat(pattern = "yyyy-MM-dd") private Date date;
...........
}