Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

19.2. Jackson

19.2.1. ObjectToJSON

			
package cn.netkiller;
import java.util.Date;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectToJSON {
  public static void main(String[] args) throws JsonProcessingException {
     Test test = new Test("Neo", 123, new Date());   
     ObjectMapper mapper = new ObjectMapper();     
     String jsonData = mapper.writerWithDefaultPrettyPrinter()
		 .writeValueAsString(test);
     System.out.println(jsonData);
  }
} 			
			
			

19.2.2. JSONToObject

			
package cn.netkiller;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONToObject {
	public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
		 String jsonData = 
		    "{"
			  +"\"name\" : \"Neo\","
			  +"\"age\" : 12,"
			  +"\"birthDate\" : \"2019-Jun-11 07:00:46 CST\""	
		   +"}";
		 ObjectMapper mapper = new ObjectMapper();
		 Test test = mapper.readValue(jsonData, Test.class);
		 System.out.println(test.getName()+" | "+test.getBirthDate()+" | "+ test.getAge());
	}
} 
			
			

19.2.3. JsonNode

			
String[] picture;
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.convertValue(picture, JsonNode.class);