差異處
這裏顯示兩個版本的差異處。
java:jackson:helloworld [2016/02/16 23:18] tony |
java:jackson:helloworld [2023/06/25 09:48] |
||
---|---|---|---|
行 1: | 行 1: | ||
- | {{tag>java jackson}} | ||
- | ====== Jackson - Hello World ====== | ||
- | ===== Introduction ===== | ||
- | 本篇內容展示Jackson的基本功能-將物件轉為json與xml格式。由於內容簡單,看程式碼就知道該怎麼做,不多做說明。 | ||
- | ===== Ivy.xml ===== | ||
- | 相依函式庫使用以下四個項目: | ||
- | <code 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(*)" /> | ||
- | </code> | ||
- | ===== Source Object ===== | ||
- | User類別是此範例中,要轉為json與xml格式的目標。在mID與mPasswd成員變數上,使用了JsonProperty annotation去描述結果要呈現的欄位名稱。以json為例,mID顯示的欄位名稱即為id;以xml為例,mID的標籤名稱為id: | ||
- | <code java> | ||
- | 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; | ||
- | } | ||
- | } | ||
- | </code> | ||
- | ===== Convert to json ===== | ||
- | <code java> | ||
- | @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); | ||
- | } | ||
- | </code> | ||
- | Output: | ||
- | <code> | ||
- | {"id":"user","passwd":"123456"} | ||
- | </code> | ||
- | ===== Convert to xml ===== | ||
- | <code java> | ||
- | @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); | ||
- | } | ||
- | </code> | ||
- | Output: | ||
- | <code xml> | ||
- | <User xmlns=""><id>user</id><passwd>123456</passwd></User> | ||
- | </code> | ||
- | |||
- | ===== ===== | ||
- | ---- | ||
- | \\ | ||
- | ~~DISQUS~~ |