JackSon converts a java object to a JSON string), jacksonjson

Source: Internet
Author: User

JackSon converts a java object to a JSON string (to), jacksonjson

Reprint Xiaojin jinyuan yuanyou:

JackSon can convert a java object to a JSON string by performing the following steps:

1. Import JackSon's jar package

2. Create an ObjectMapper object

3. Use the writeValueAsString () method of the ObjectMapper object to convert a java object to a JSON object.

Here is an example:

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);    }}

Output The following JSON string to the console:

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

Note: JackSon uses the getter Method to Determine the attributes of the JSON object. For example, if the preceding getDate () method is changed to getFruitDate (), the date in the JSON string displayed on the console is changed to fruitdate; at the same time, there is an annotation @ JsonIgnore. When this annotation is added before a getter () method, the JSON string ignores this attribute.

Address: https://www.cnblogs.com/hamihua/p/6684166.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.