下面演示使用 Jackson 實現(xiàn) Java 對象和 JSON 的相互轉(zhuǎn)換。
1. 快速參考
1.1 Java object to JSON, writeValue(...)
ObjectMapper mapper = new ObjectMapper();
Staff obj = new Staff();
//Object to JSON in file
mapper.writeValue(new File("c:\\file.json"), obj);
//Object to JSON in String
String jsonInString = mapper.writeValueAsString(obj);
1.2 JSON to Java object readValue(...)
ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mjw'}";
//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
//JSON from URL to Object
Staff obj = mapper.readValue(new URL("http://www.lxweimin.com/u/c38e94dcec65"), Staff.class);
//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);
2. POJO
Plain Old Java Object, 表示常規(guī)的Java對象,沒有擴展特定的類,或者實現(xiàn)特定的接口,或者說不受特定框架擴展的影響。
例如,如果想從 JMS 接收信息,則需要實現(xiàn) MessageListener 接口:
public class ExampleListener implements MessageListener {
public void onMessage(Message message){
...
}
}
這個類和JMS的 MessageListener 接口綁定,因此難以遷移到其他的信息處理框架,它不是POJO。
3. Java 和 JSON 的相互轉(zhuǎn)換
下面通過一個實例,說明如何使用 Jackson 實現(xiàn)JSON和Java對象相互轉(zhuǎn)換。
Album 類,包含一個字段:
class Album {
private String title;
public Album(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
3.1 使用 ObjectMapper 進行轉(zhuǎn)換
Jackson 默認使用 BeanSerializer 序列化POJO,要求對應(yīng)的字段為 public,或者有對應(yīng)的 getter 方法。
單字段序列化
Album album = new Album("Kind Of Blue");
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(System.out, album);
輸出:
{"title":"Kind Of Blue"}
數(shù)組序列化
現(xiàn)在繼續(xù)向 Album 添加一個數(shù)組字段及對應(yīng)的 getter 和 setter 方法:
private String[] links;
public String[] getLinks(){
return links;
}
public void setLinks(String[] links){
this.links = links;
}
修改 main 方法:
Album album = new Album("Kind Of Blue");
album.setLinks(new String[]{"link1", "link2"});
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(System.out, album);
輸出:
{"title":"Kind Of Blue","links":["link1","link2"]}
List 序列化
向 Album 添加 List 字段:
private List<String> songs;
public List<String> getSongs(){
return songs;
}
public void setSongs(List<String> songs){
this.songs = songs;
}
修改 main 方法:
Album album = new Album("Kind Of Blue");
album.setLinks(new String[]{"link1", "link2"});
List<String> songs = new ArrayList<>();
songs.add("So what");
songs.add("Flamenco Sketches");
songs.add("Freddie Freeloader");
album.setSongs(songs);
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(System.out, album);
輸出:
{"title":"Kind Of Blue","links":["link1","link2"],"songs":["So what","Flamenco Sketches","Freddie Freeloader"]}
從輸出結(jié)構(gòu)可以看到,List和數(shù)組的輸出格式是一樣的。
Java 對象序列化
Java 對象,序列化后在JSON中被 {} 括起來。
定義Artist 類:
public class Artist{
public String name;
public Date birthDate;
}
在Album 中添加對應(yīng)的字段,并在 main 中設(shè)置其值:
Artist artist = new Artist();
artist.name = "Miles Davis";
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
artist.birthDate = format.parse("26-05-1926");
album.setArtist(artist);
輸出:
{"title":"Kind Of Blue","links":["link1","link2"],"songs":["So what","Flamenco Sketches","Freddie Freeloader"],"artist":{"name":"Miles Davis","birthDate":-1376035200000}}
格式化輸出
配置 ObjectMapper ,可以讓輸出更好看一些:
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
此時的JSON輸出如下:
{
"title" : "Kind Of Blue",
"links" : [ "link1", "link2" ],
"songs" : [ "So what", "Flamenco Sketches", "Freddie Freeloader" ],
"artist" : {
"name" : "Miles Davis",
"birthDate" : -1376035200000
}
}
Map 序列化
向 Album 中添加如下內(nèi)容:
private Map<String, String> musicians = new HashMap<>();
public Map<String, String> getMusicians(){
return Collections.unmodifiableMap(musicians);
}
public void addMusician(String key, String value){
musicians.put(key, value);
}
在 main 中添加如下內(nèi)容:
album.addMusician("Miles Davis", "Trumpet, Band leader");
album.addMusician("Julian Adderley", "Alto Saxophone");
album.addMusician("Paul Chambers", "double bass");
輸出如下:
{
"title" : "Kind Of Blue",
"links" : [ "link1", "link2" ],
"songs" : [ "So what", "Flamenco Sketches", "Freddie Freeloader" ],
"artist" : {
"name" : "Miles Davis",
"birthDate" : -1376035200000
},
"musicians" : {
"Miles Davis" : "Trumpet, Band leader",
"Paul Chambers" : "double bass",
"Julian Adderley" : "Alto Saxophone"
}
}
其他
設(shè)置輸出時間格式
SimpleDateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
mapper.setDateFormat(outputFormat);
讓Map按序輸出
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
此時輸出:
{
"title" : "Kind Of Blue",
"links" : [ "link1", "link2" ],
"songs" : [ "So what", "Flamenco Sketches", "Freddie Freeloader" ],
"artist" : {
"name" : "Miles Davis",
"birthDate" : "26 May 1926"
},
"musicians" : {
"Julian Adderley" : "Alto Saxophone",
"Miles Davis" : "Trumpet, Band leader",
"Paul Chambers" : "double bass"
}
}
3.2 使用 Tree Model 進行轉(zhuǎn)換
我們繼續(xù)使用上面的例子,來演示 Tree Model 的使用。使用 Tree 進行輸出包含如下幾個步驟:
- 創(chuàng)建 JsonNodeFactory,用于創(chuàng)建 node。
- 使用JsonFactory創(chuàng)建 JsonGenerator,并指定輸出方法。
- 創(chuàng)建ObjectMapper,它使用 JsonGenerator 和樹的根節(jié)點輸出到JSON。
如下所示:
public class SerializationExampleTreeModel{
public static void main(String[] args) throws IOException{
JsonNodeFactory factory = new JsonNodeFactory(false);
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator generator = jsonFactory.createGenerator(System.out);
ObjectMapper mapper = new ObjectMapper();
ObjectNode album = factory.objectNode();
mapper.writeTree(generator, album);
}
}
由于沒有添加任何實質(zhì)性內(nèi)容,所以輸出為:
{}
開始添加內(nèi)容:
album.put("Album-Title", "Kind Of Blue");
JSON:
{"Album-Title":"Kind Of Blue"}
添加數(shù)組:
ArrayNode links = factory.arrayNode();
links.add("link1").add("link2");
album.set("links", links);
JSON:
{"Album-Title":"Kind Of Blue","links":["link1","link2"]}
添加對象:
ObjectNode artist = factory.objectNode();
artist.put("Artist-Name", "Miles Davis");
artist.put("birthDate", "26 May 1926");
album.set("artist", artist);
JSON:
{"Album-Title":"Kind Of Blue","links":["link1","link2"],"artist":{"Artist-Name":"Miles Davis","birthDate":"26 May 1926"}}
添加 musicians:
ObjectNode musicians = factory.objectNode();
musicians.put("Julian Adderley", "Alto Saxophone");
musicians.put("Miles Davis", "Trumpet, Band leader");
album.set("musicians", musicians);
JSON:
{"Album-Title":"Kind Of Blue","links":["link1","link2"],"artist":{"Artist-Name":"Miles Davis","birthDate":"26 May 1926"},"musicians":{"Julian Adderley":"Alto Saxophone","Miles Davis":"Trumpet, Band leader"}}