標籤:main div his json void 忽略 val ajax public
什麼是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"}]
於是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());
//注意"的轉義操作
轉換JSON工具——Jackson的簡單使用