Introduction
本篇內容展示Jackson的基本功能-將物件轉為json與xml格式。由於內容簡單,看程式碼就知道該怎麼做,不多做說明。
Ivy.xml
相依函式庫使用以下四個項目:
<dependency org="com.fasterxml.jackson.core" name="jackson-core" rev="latest.integration" conf="default->default(*)" /> <dependency org="com.fasterxml.jackson.core" name="jackson-annotations" rev="latest.integration" conf="default->default(*)" /> <dependency org="com.fasterxml.jackson.core" name="jackson-databind" rev="latest.integration" conf="default->default(*)" /> <dependency org="com.fasterxml.jackson.dataformat" name="jackson-dataformat-xml" rev="latest.integration" conf="default->default(*)" />
Source Object
User類別是此範例中,要轉為json與xml格式的目標。在mID與mPasswd成員變數上,使用了JsonProperty annotation去描述結果要呈現的欄位名稱。以json為例,mID顯示的欄位名稱即為id;以xml為例,mID的標籤名稱為id:
package org.tonylin.practice.jackson; import com.fasterxml.jackson.annotation.JsonProperty; public class User { @JsonProperty(value="id") private String mID; @JsonProperty(value="passwd") private String mPasswd; public String getmID() { return mID; } public void setID(String aID) { this.mID = aID; } public String getPasswd() { return mPasswd; } public void setPasswd(String aPasswd) { this.mPasswd = aPasswd; } }
這裡必須特別注意的是,Jackson會優先使用get method為欄位名稱。下面這個範例所輸出的ss值為test而不是test2,即使對ss加上@JsonProperty(value=“ss”)也是test:
public String ss = "test2"; public String getSS(){ return "test"; }
一般的member宣告會使用m開頭,如果@JsonProperty的value和get method不同,就會導致同時輸出method欄位與@JsonProperty宣告的欄位:
@JsonProperty(value="s1") private String mss = "test2"; public String getSS(){ return "test"; }
Output:
"ss":"test","s1":"test2"
Convert to json
@Test public void testJsonGenerator() throws IOException { ObjectMapper mapper = new ObjectMapper(); JsonGenerator generator = mapper.getFactory().createGenerator(System.out); User u = new User(); u.setID("user"); u.setPasswd("123456"); generator.writeObject(u); }
Output:
{"id":"user","passwd":"123456"}
Convert to xml
@Test public void testXmlGenerator() throws IOException { XmlMapper mapper = new XmlMapper(); JsonGenerator generator = mapper.getFactory().createGenerator(System.out); User u = new User(); u.setID("user"); u.setPasswd("123456"); generator.writeObject(u); }
Output:
<User xmlns=""><id>user</id><passwd>123456</passwd></User>
留言
張貼留言