什么是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());
//注意"的轉義操作