什么是Jackson
可以轻松实现Java对象与JSON字符串的转换
准备工作:导包
Jackson的jar all下载地址:http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.jar
1.实体对象转JSON
jackson使用getter方法定位属性(而不是字段)
可以通过添加注解 @JsonIgnore 使某些getter来进行忽略
将对象或集合转为json字符串
package cn.jackson;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class Customer {
private String name;
private String id;
public Customer() {
super();
}
public Customer(String name, String id) {
super();
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@JsonIgnore
public String getCity(){
return "北京";
}
public String getBirth(){
return "1988";
}
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
//导包
//创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
//
Customer cust = new Customer("jackson", "1001");
String jsonStr = mapper.writeValueAsString(cust);
System.out.println(jsonStr);
List<Customer> list = (List) Arrays.asList(cust,new Customer("33","离魂计"));
String jsonStrList = mapper.writeValueAsString(list);
System.out.println(jsonStrList);
/**
* jackson使用getter方法定位属性
* 可以通过添加注解 @JsonIgnore 使某些getter来进行忽略
*/
}
}
结果:
{"name":"jackson","id":"1001","birth":"1988"}
[{"name":"jackson","id":"1001","birth":"1988"},{"name":"33","id":"离魂计","birth":"1988"}]
在SpringMVC中,如果想自定义转换成JSON时的key不是属性的名称,例如 String name 转换时变成 "name":"xxx",如果想变成"n":"xxx",可以使用注解!
@JsonPropertity("n")
private String name
于是ajax_day02可以转为使用Jackson简化:
ObjectMapper mapper=new ObjectMapper();
String result=mapper.writeValueAsString(sc);
2.JSON字符串转对象
ObjectMapper mapper = new ObjectMapper();
String json = "{"name":"jackson","id":"1001"}";
Customer c = mapper.readValue(json, Customer.class);
System.out.println(c.getId());
//注意"的转义操作