Jackson常用方法以及jacksonUtil工具類詳解
前言:
項(xiàng)目中我們通常使用ajax返回json數(shù)據(jù)格式的形式進(jìn)行前后端數(shù)據(jù)交互,所以會(huì)用到j(luò)ava數(shù)據(jù)json數(shù)據(jù)互相轉(zhuǎn)化,通常我們的做法是在項(xiàng)目中創(chuàng)建一個(gè)工具類進(jìn)行轉(zhuǎn)化處理。
如下:
我的demo包含了項(xiàng)目中常用的jacksonUtil類,以及常用的JSON JAVA處理數(shù)據(jù)轉(zhuǎn)化處理方法。
項(xiàng)目結(jié)構(gòu)以及引用jar包如下,jar包中的junit是用于單元測(cè)試,與jackson及其相關(guān)的包無關(guān)。
每個(gè)部分我都加了注釋,直接copy下來運(yùn)行就可以查看具體效果,下面直接上代碼:

實(shí)體類book:
package test.entity;
public class Book {
private int bookId;//書的ID
private String author;//作者
private String name;//書名
private int price;//書價(jià)
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Book [bookId=" + bookId + ", author=" + author + ", name="
+ name + ", price=" + price + "]";
}
}
jackson以及相關(guān)jar包對(duì)java以及json數(shù)據(jù)的具體處理方法,JackSonDemo類。
package test.jackson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import test.entity.Book;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JackSonDemo {
private JsonGenerator jsonGenerator = null;
private ObjectMapper objectMapper = null;
private Book book = null;
/**
* Junit的方法,用于給每個(gè)單元測(cè)試添加前置條件和結(jié)束條件
*/
@Before
public void init() {
// 構(gòu)建一個(gè)Book實(shí)例對(duì)象并賦值
book = new Book();
book.setAuthor("海明威");
book.setBookId(123);
book.setName("老人與海");
book.setPrice(30);
objectMapper = new ObjectMapper();
try {
jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
System.out, JsonEncoding.UTF8);
} catch (IOException e) {
e.printStackTrace();
}
}
@After
public void destory() {
try {
if (jsonGenerator != null) {
jsonGenerator.flush();
}
if (!jsonGenerator.isClosed()) {
jsonGenerator.close();
}
jsonGenerator = null;
objectMapper = null;
book = null;
System.gc();
} catch (IOException e) {
e.printStackTrace();
}
}
/********************** java常見數(shù)據(jù)類型轉(zhuǎn)JSON ****************************/
/**
* 1.javaBean轉(zhuǎn)化成json---兩種方法writeObject/writeValue均可
* jsonGenerator依賴于ObjectMapper創(chuàng)建
*/
@Test
public void javaBeanToJson() {
try {
System.out.println("jsonGenerator");
// 方法一
jsonGenerator.writeObject(book);
System.out.println();
System.out.println("ObjectMapper");
// 方法二
objectMapper.writeValue(System.out, book);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* List轉(zhuǎn)化成JSON,三種方式
*/
@Test
public void listToJson() {
try {
List<Book> list = new ArrayList<Book>();
Book bookOne = new Book();
bookOne.setAuthor("安徒生");
bookOne.setBookId(456);
bookOne.setName("安徒生童話");
bookOne.setPrice(55);
Book bookTwo = new Book();
bookTwo.setAuthor("安徒生");
bookTwo.setBookId(456);
bookTwo.setName("安徒生童話");
bookTwo.setPrice(55);
list.add(bookOne);
list.add(bookTwo);
// 方式一
System.out.println("方式一jsonGenerator");
jsonGenerator.writeObject(list);
System.out.println();
System.out.println("方式二ObjectMapper");
// 方式二
System.out.println(objectMapper.writeValueAsString(list));
// 方式三
System.out.println("方式三直接通過objectMapper的writeValue方法:");
objectMapper.writeValue(System.out, list);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* map轉(zhuǎn)化成JSON,兩種方式
*/
@Test
public void mapToJSON() {
try {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", book.getName());
map.put("book", book);
Book newBook = new Book();
newBook.setAuthor("安徒生");
newBook.setBookId(456);
newBook.setName("安徒生童話");
newBook.setPrice(55);
map.put("newBook", newBook);
System.out.println("第一種方式j(luò)sonGenerator");
jsonGenerator.writeObject(map);
System.out.println("");
System.out.println("第二種方式objectMapper");
objectMapper.writeValue(System.out, map);
} catch (IOException e) {
e.printStackTrace();
}
}
/*********************** JSON數(shù)據(jù)類型轉(zhuǎn)java數(shù)據(jù) ********************************/
/**
* json'對(duì)象'數(shù)據(jù)轉(zhuǎn)化成javaBean
*/
@Test
public void jsonToJavaBean() {
String json = "{\"bookId\":\"11111\",\"author\":\"魯迅\",\"name\":\"朝花夕拾\",\"price\":\"45\"}";
try {
Book book = objectMapper.readValue(json, Book.class);
System.out.println(book);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* json'數(shù)組'數(shù)據(jù)轉(zhuǎn)化為ArrayList
*/
@Test
public void jsonToArrayList() {
String json = "[{\"bookId\":\"11111\",\"author\":\"魯迅\",\"name\":\"朝花夕拾\",\"price\":\"45\"},"
+ "{\"bookId\":\"11111\",\"author\":\"魯迅\",\"name\":\"朝花夕拾\",\"price\":\"45\"}]";
try {
Book[] book = objectMapper.readValue(json, Book[].class);
for (int i = 0; i < book.length; i++) {
// 注意book[i]僅僅是數(shù)組,需要通過Arrays.asList()方法轉(zhuǎn)為ArrayList
List<Book> list = Arrays.asList(book[i]);
System.out.println(list);
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* json轉(zhuǎn)換成map
*/
@Test
public void JsonToMap() {
String json = "{\"name\":\"book\",\"number\":\"12138\",\"book1\":{\"bookId\":\"11111\",\"author\":\"魯迅\",\"name\":\"朝花夕拾\",\"price\":\"45\"},"
+ "\"book2\":{\"bookId\":\"22222\",\"author\":\"易中天\",\"name\":\"祖先\",\"price\":\"25\"}}";
try {
Map<String, Map<String, Object>> maps = objectMapper.readValue(
json, Map.class);
Set<String> key = maps.keySet();
Iterator<String> iter = key.iterator();
while (iter.hasNext()) {
String field = iter.next();
System.out.println(field + ":" + maps.get(field));
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最后,是我們?cè)趯?shí)際開發(fā)項(xiàng)目中使用的jacksonUtil類,應(yīng)用起來很簡單,直接jacksonUtil.bean2Json(Object object)(bean轉(zhuǎn)JSON)或者jacksonUtil.json2Bean(Object object)(JSON轉(zhuǎn)bean)
package test.util;
import java.io.IOException;
import java.io.StringWriter;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* bean轉(zhuǎn)json格式或者json轉(zhuǎn)bean格式, 項(xiàng)目中我們通常使用這個(gè)工具類進(jìn)行json---java互相轉(zhuǎn)化
*/
public class JacksonUtil {
private static ObjectMapper mapper = new ObjectMapper();
public static String bean2Json(Object obj) throws IOException {
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
mapper.writeValue(gen, obj);
gen.close();
return sw.toString();
}
public static <T> T json2Bean(String jsonStr, Class<T> objClass)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(jsonStr, objClass);
}
}
Jackson工具類(各種轉(zhuǎn)換)
首先要在項(xiàng)目中引入jackson的jar包(在此不做說明)
下面直接上代碼
public class JacksonUtils {
private final static ObjectMapper objectMapper = new ObjectMapper();
private JacksonUtils() {
}
public static ObjectMapper getInstance() {
return objectMapper;
}
/**
* javaBean、列表數(shù)組轉(zhuǎn)換為json字符串
*/
public static String obj2json(Object obj) throws Exception {
return objectMapper.writeValueAsString(obj);
}
/**
* javaBean、列表數(shù)組轉(zhuǎn)換為json字符串,忽略空值
*/
public static String obj2jsonIgnoreNull(Object obj) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsString(obj);
}
/**
* json 轉(zhuǎn)JavaBean
*/
public static <T> T json2pojo(String jsonString, Class<T> clazz) throws Exception {
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return objectMapper.readValue(jsonString, clazz);
}
/**
* json字符串轉(zhuǎn)換為map
*/
public static <T> Map<String, Object> json2map(String jsonString) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.readValue(jsonString, Map.class);
}
/**
* json字符串轉(zhuǎn)換為map
*/
public static <T> Map<String, T> json2map(String jsonString, Class<T> clazz) throws Exception {
Map<String, Map<String, Object>> map = objectMapper.readValue(jsonString, new TypeReference<Map<String, T>>() {
});
Map<String, T> result = new HashMap<String, T>();
for (Map.Entry<String, Map<String, Object>> entry : map.entrySet()) {
result.put(entry.getKey(), map2pojo(entry.getValue(), clazz));
}
return result;
}
/**
* 深度轉(zhuǎn)換json成map
*
* @param json
* @return
*/
public static Map<String, Object> json2mapDeeply(String json) throws Exception {
return json2MapRecursion(json, objectMapper);
}
/**
* 把json解析成list,如果list內(nèi)部的元素存在jsonString,繼續(xù)解析
*
* @param json
* @param mapper 解析工具
* @return
* @throws Exception
*/
private static List<Object> json2ListRecursion(String json, ObjectMapper mapper) throws Exception {
if (json == null) {
return null;
}
List<Object> list = mapper.readValue(json, List.class);
for (Object obj : list) {
if (obj != null && obj instanceof String) {
String str = (String) obj;
if (str.startsWith("[")) {
obj = json2ListRecursion(str, mapper);
} else if (obj.toString().startsWith("{")) {
obj = json2MapRecursion(str, mapper);
}
}
}
return list;
}
/**
* 把json解析成map,如果map內(nèi)部的value存在jsonString,繼續(xù)解析
*
* @param json
* @param mapper
* @return
* @throws Exception
*/
private static Map<String, Object> json2MapRecursion(String json, ObjectMapper mapper) throws Exception {
if (json == null) {
return null;
}
Map<String, Object> map = mapper.readValue(json, Map.class);
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object obj = entry.getValue();
if (obj != null && obj instanceof String) {
String str = ((String) obj);
if (str.startsWith("[")) {
List<?> list = json2ListRecursion(str, mapper);
map.put(entry.getKey(), list);
} else if (str.startsWith("{")) {
Map<String, Object> mapRecursion = json2MapRecursion(str, mapper);
map.put(entry.getKey(), mapRecursion);
}
}
}
return map;
}
/**
* 與javaBean json數(shù)組字符串轉(zhuǎn)換為列表
*/
public static <T> List<T> json2list(String jsonArrayStr, Class<T> clazz) throws Exception {
JavaType javaType = getCollectionType(ArrayList.class, clazz);
List<T> lst = (List<T>) objectMapper.readValue(jsonArrayStr, javaType);
return lst;
}
/**
* 獲取泛型的Collection Type
*
* @param collectionClass 泛型的Collection
* @param elementClasses 元素類
* @return JavaType Java類型
* @since 1.0
*/
public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
/**
* map 轉(zhuǎn)JavaBean
*/
public static <T> T map2pojo(Map map, Class<T> clazz) {
return objectMapper.convertValue(map, clazz);
}
/**
* map 轉(zhuǎn)json
*
* @param map
* @return
*/
public static String mapToJson(Map map) {
try {
return objectMapper.writeValueAsString(map);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* map 轉(zhuǎn)JavaBean
*/
public static <T> T obj2pojo(Object obj, Class<T> clazz) {
return objectMapper.convertValue(obj, clazz);
}
}
導(dǎo)入相應(yīng)的包 就可以使用,個(gè)人覺得還是挺方便的!
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
org.apache.zookeeper.KeeperException.BadVersionException異常的解
在使用Apache ZooKeeper進(jìn)行分布式協(xié)調(diào)時(shí),你可能會(huì)遇到org.apache.zookeeper.KeeperException.BadVersionException異常,本文就來介紹一下解決方法,感興趣的可以了解一下2024-03-03
詳解eclipse創(chuàng)建maven項(xiàng)目實(shí)現(xiàn)動(dòng)態(tài)web工程完整示例
這篇文章主要介紹了詳解eclipse創(chuàng)建maven項(xiàng)目實(shí)現(xiàn)動(dòng)態(tài)web工程完整示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12
加速spring/springboot應(yīng)用啟動(dòng)速度詳解
這篇文章主要介紹了加速spring/springboot應(yīng)用啟動(dòng)速度詳解,本文通過實(shí)例代碼給大家介紹的非常詳細(xì)對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
Spring自動(dòng)裝配之方法、構(gòu)造器位置的自動(dòng)注入操作
這篇文章主要介紹了Spring自動(dòng)裝配之方法、構(gòu)造器位置的自動(dòng)注入操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
Java語言面向?qū)ο缶幊趟枷胫惻c對(duì)象實(shí)例詳解
這篇文章主要介紹了Java語言面向?qū)ο缶幊趟枷胫惻c對(duì)象實(shí)例詳解,還是十分不錯(cuò)的,這里給大家分享下,需要的朋友可以參考。2017-10-10

