Jackson的使用
1、Jackson可以将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。性能要比json-lib相对高些。
2、涉及到的jar包:
--jackson-annotations-2.2.2.jar
--jackson-core-2.2.2.jar
--jackson-databind-2.2.2.jar
3、测试:将JavaBean转为Json字符串
--Customer类:
package com.tt.test; public class Customer { private String name; private int age; public Customer(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getCity(){ return "BJ"; } public String getBirth(){ return "1990-12-11"; } }
--使用ObjectMapper对象的writeValueAsString()方法将Customer对象转为Json字符串:
public void testJackson() throws JsonProcessingException { Customer customer = new Customer("tt", 22); ObjectMapper mapper = new ObjectMapper(); String jsonStr = mapper.writeValueAsString(customer); System.out.println(jsonStr); }
--输出结果为:
{"name":"tt","age":22,"city":"BJ","birth":"1990-12-11"}
--注意:Jackson根据getter来定位Json对象的属性,而不是自定义的字段;
--可以在getter方法上添加 @JsonIgnore 注解来忽略相应的属性;