Home | 简体中文 | 繁体中文 | 杂文 | 知乎专栏 | Github | OSChina 博客 | 云社区 | 云栖社区 | Facebook | Linkedin | 视频教程 | 打赏(Donations) | About
知乎专栏多维度架构

22.2. Jackson

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

22.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());
	}
} 
			
			

22.2.3. JsonNode

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