Jackson常⽤⽅法以及jacksonUtil⼯具类详解
前⾔:
项⽬中我们通常使⽤ajax返回json数据格式的形式进⾏前后端数据交互,所以会⽤到java数据json数据互相转化,通常我们的做法是在项⽬中创建⼀个⼯具类进⾏转化处理。
如下:
我的demo包含了项⽬中常⽤的jacksonUtil类,以及常⽤的JSON JAVA处理数据转化处理⽅法。
项⽬结构以及引⽤jar包如下,jar包中的junit是⽤于单元测试,与jackson及其相关的包⽆关。
每个部分我都加了注释,直接copy下来运⾏就可以查看具体效果,下⾯直接上代码:
实体类book:
ity;
public class Book {
private int bookId;//书的ID
private String author;//作者
private String name;//书名
private int price;//书价
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以及相关jar包对java以及json数据的具体处理⽅法,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;
ity.Book;
import com.JsonEncoding;
import com.JsonGenerator;
import com.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的⽅法,⽤于给每个单元测试添加前置条件和结束条件
*/
@Before
public void init() {
// 构建⼀个Book实例对象并赋值
book = new Book();
book.setAuthor("海明威");
book.setBookId(123);
book.setName("⽼⼈与海");
book.setPrice(30);
objectMapper = new ObjectMapper();
try {
jsonGenerator = JsonFactory().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;
<();
} catch (IOException e) {
e.printStackTrace();
}
}
/********************** java常见数据类型转JSON ****************************/ /**
* 1.javaBean转化成json---两种⽅法writeObject/writeValue均可
* jsonGenerator依赖于ObjectMapper创建
*/
@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转化成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转化成JSON,两种⽅式
*/
@Test
public void mapToJSON() {
try {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", Name());
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("第⼀种⽅式jsonGenerator");
jsonGenerator.writeObject(map);
System.out.println("");
System.out.println("第⼆种⽅式objectMapper");
objectMapper.writeValue(System.out, map);
} catch (IOException e) {
e.printStackTrace();
}
}
/*********************** JSON数据类型转java数据 ********************************/
/**
* json'对象'数据转化成javaBean
*/
@Test
public void jsonToJavaBean() {
String json = "{\"bookId\":\"11111\",\"author\":\"鲁迅\",\"name\":\"朝花⼣拾\",\"price\":\"45\"}";
try {
Book book = adValue(json, Book.class);
System.out.println(book);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* json'数组'数据转化为ArrayList
*/
@Test
public void jsonToArrayList() {
String json = "[{\"bookId\":\"11111\",\"author\":\"鲁迅\",\"name\":\"朝花⼣拾\",\"price\":\"45\"},"
+ "{\"bookId\":\"11111\",\"author\":\"鲁迅\",\"name\":\"朝花⼣拾\",\"price\":\"45\"}]";
try {
Book[] book = adValue(json, Book[].class);
for (int i = 0; i < book.length; i++) {
// 注意book[i]仅仅是数组,需要通过Arrays.asList()⽅法转为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转换成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 = adValue(
json, Map.class);
Set<String> key = maps.keySet();
Iterator<String> iter = key.iterator();
while (iter.hasNext()) {
String field = ();
System.out.println(field + ":" + (field));
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最后,是我们在实际开发项⽬中使⽤的jacksonUtil类,应⽤起来很简单,直接jacksonUtil.bean2Json(Object object)(bean转JSON)或者jacksonUtil.json2Bean(Object object)(JSON转bean)
package test.util;
import java.io.IOException;
import java.io.StringWriter;
import com.JsonFactory;
import com.JsonGenerator;
import com.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* bean转json格式或者json转bean格式, 项⽬中我们通常使⽤这个⼯具类进⾏json---java互相转化
*/
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();
String();
}
public static <T> T json2Bean(String jsonStr, Class<T> objClass)
throws JsonParseException, JsonMappingException, IOException {
adValue(jsonStr, objClass);
}
}
Jackson⼯具类(各种转换)
⾸先要在项⽬中引⼊jackson的jar包(在此不做说明)
下⾯直接上代码
public class JacksonUtils {
private final static ObjectMapper objectMapper = new ObjectMapper();
private JacksonUtils() {
}
public static ObjectMapper getInstance() {
return objectMapper;
}
/**
* javaBean、列表数组转换为json字符串
*/
public static String obj2json(Object obj) throws Exception {
return objectMapper.writeValueAsString(obj);
}
/**
* javaBean、列表数组转换为json字符串,忽略空值
*/
public static String obj2jsonIgnoreNull(Object obj) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsString(obj);
}
/**
* json 转JavaBean
*/
public static <T> T json2pojo(String jsonString, Class<T> clazz) throws Exception {
adValue(jsonString, clazz);
}
/**
* json字符串转换为map
*/
public static <T> Map<String, Object> json2map(String jsonString) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。