轉換JSON工具——Jackson的簡單使用

來源:互聯網
上載者:User

標籤: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的簡單使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.