JackSon將java對象轉換為JSON字串),jacksonjson

來源:互聯網
上載者:User

JackSon將java對象轉換為JSON字串(轉),jacksonjson

轉載小金金金丶園友:

JackSon可以將java對象轉換為JSON字串,步驟如下:

1.匯入JackSon 的jar包

2.建立ObjectMapper對象

3.使用ObjectMapper對象的writeValueAsString()方法將java對象轉換為JSON對象

這裡有個例子:

public class Fruit {    private String name;    private String id;    public Customet(String name, String id) {        super();        this.name = name;        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    //@JsonIgnore    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getDate(){        return "2017-04-09";    }    public static void main(String[] args) throws JsonProcessingException {        ObjectMapper mapper = new ObjectMapper();        Fruit fruit= new Fruit("HaMiGua", "1001");        String mapJakcson = mapper.writeValueAsString(fruit);        System.out.println(mapJakcson);    }}

通過輸出到控制台顯示如下JSON字串

{"name":"HaMiGua","id":"1001","date":"2017-04-09"}

注意:JackSon是通過getter方法確定JSON對象屬性的,比如說上面的getDate()方法,如果改成getFruitDate(),則控制台顯示的JSON字串中的date變為fruitdate;同時這裡有一個註解@JsonIgnore,當在一個getter()方法前加上此註解,則JSON字串會忽略此屬性。

原文地址:https://www.cnblogs.com/hamihua/p/6684166.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.