Jackson 介紹java
Jackson框架是基於Java平臺的一套數據處理工具,被稱爲「最好的Java Json解析器」。
Jackson框架包含了3個核心庫:streaming,databind,annotations。git
Jackson Home Page:https://github.com/FasterXML/jackson
Jackson Wiki:http://wiki.fasterxml.com/JacksonHome
Jackson doc: https://github.com/FasterXML/jackson-docs
Jackson Download Page:http://wiki.fasterxml.com/JacksonDownloadgithub
Jackson能夠作什麼apache
xml、csv和java對象互轉json
Jackson的使用app
Jackson提供了三種可選的Json處理方法:流式API(Streaming API) 、樹模型(Tree Model)、數據綁定(Data Binding)。框架
從使用角度來看,比較一下這三種處理Json的方式的特性:
Streaming API:是效率最高的處理方式(開銷低、讀寫速度快,但程序編寫複雜度高)
Tree Model:是最靈活的處理方式
Data Binding:是最經常使用的處理方式工具
Jacson經常使用配置選項學習
/**序列化配置*/ ObjectMapper mapper = new ObjectMapper(); // 設置日期處理格式 SimpleDateFormat dateFormat = new SimpleDateFormat(「yyyy-MM-dd」); mapper.setDateFormat(dateFormat); // 美化json輸出 mapper.configure(SerializationFeature.INDENT_OUTPUT, true); //忽略空屬性 mapper.setSerializationInclusion(Include.NON_EMPTY); /**反序列化配置*/ ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
常見問題ui
1. json字符串轉java對象,json中存在一個字段,但java對象中沒有該字段,會拋出UnrecognizedPropertyException
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
package test.json; import java.io.Serializable; import org.apache.commons.lang.builder.ToStringBuilder; import org.junit.Test; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class TestJson { @Test public void jsonToClass() { String s = "{\"id\":1,\"name\":\"test\",\"flag\":true,\"age\":19}"; ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); TE t; try { t = mapper.readValue(s, TE.class); System.out.println(ToStringBuilder.reflectionToString(t)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class TE implements Serializable { /** * */ private static final long serialVersionUID = 1L; private long id; private String name; private boolean flag; //private int age; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } /*public int getAge() { return age; } public void setAge(int age) { this.age = age; }*/ }
參考