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