前言:
项目中我们通常使用ajax返回json数据格式的形式进行前后端数据交互,所以会用到java数据json数据互相转化,通常我们的做法是在项目中创建一个工具类进行转化处理。
如下:
我的demo包含了项目中常用的jacksonUtil类,以及常用的JSON JAVA处理数据转化处理方法。
项目结构以及引用jar包如下,jar包中的junit是用于单元测试,与jackson及其相关的包无关。
每个部分我都加了注释,直接copy下来运行就可以查看具体效果,下面直接上代码:
实体类book:
package test.entity;
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;
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;
@Before
public void init() {
// 构建一个Book实例对象并赋值
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();
}
}
@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();
}
}
@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();
}
}
@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("第一种方式jsonGenerator");
jsonGenerator.writeObject(map);
System.out.println("");
System.out.println("第二种方式objectMapper");
objectMapper.writeValue(System.out, map);
} catch (IOException e) {
e.printStackTrace();
}
}
@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();
}
}
@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]仅仅是数组,需要通过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();
}
}
@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();
}
}
}
最后,是我们在实际开发项目中使用的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.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;
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工具类(各种转换)
首先要在项目中引入jackson的jar包(在此不做说明)
下面直接上代码
public class JacksonUtils {
private final static ObjectMapper objectMapper = new ObjectMapper();
private JacksonUtils() {
}
public static ObjectMapper getInstance() {
return objectMapper;
}
public static String obj2json(Object obj) throws Exception {
return objectMapper.writeValueAsString(obj);
}
public static String obj2jsonIgnoreNull(Object obj) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsString(obj);
}
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);
}
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);
}
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;
}
public static Map<String, Object> json2mapDeeply(String json) throws Exception {
return json2MapRecursion(json, objectMapper);
}
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;
}
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;
}
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;
}
public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
public static <T> T map2pojo(Map map, Class<T> clazz) {
return objectMapper.convertValue(map, clazz);
}
public static String mapToJson(Map map) {
try {
return objectMapper.writeValueAsString(map);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static <T> T obj2pojo(Object obj, Class<T> clazz) {
return objectMapper.convertValue(obj, clazz);
}
}
导入相应的包 就可以使用,个人觉得还是挺方便的!
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。