Jackson 상용 방법 및 jacksonUtil 도구 류 상세 설명
16599 단어 JacksonjacksonUtil도구 클래스
프로젝트 에서 우 리 는 보통 ajax 를 사용 하여 json 데이터 형식 으로 돌아 가 전후 단 데이터 교 류 를 하기 때문에 자바 데이터 json 데이터 로 서로 전환 합 니 다.보통 우리 의 방법 은 프로젝트 에서 도구 류 를 만들어 전환 처 리 를 하 는 것 입 니 다.
다음 과 같다.
제 demo 는 프로젝트 에서 자주 사용 하 는 jacksonUtil 류 와 자주 사용 하 는 JSON JAVA 처리 데이터 전환 처리 방법 을 포함 합 니 다.
프로젝트 구조 및 참조 jar 가방 은 다음 과 같 습 니 다.jar 가방 의 준 it 는 유닛 테스트 에 사 용 됩 니 다.jackson 과 관련 된 가방 과 무관 합 니 다.
모든 부분 에 주석 을 달 았 습 니 다.복사 해서 실행 하면 구체 적 인 효 과 를 볼 수 있 습 니 다.아래 에 코드 를 직접 올 립 니 다.
실체 클래스 북:
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 패키지 가 자바 및 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;
/**
* Junit ,
*/
@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();
}
}
/********************** 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", 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();
}
}
/*********************** JSON java ********************************/
/**
* json' ' 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' ' 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] , 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 = 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;
/**
* 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();
return sw.toString();
}
public static <T> T json2Bean(String jsonStr, Class<T> objClass)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(jsonStr, objClass);
}
}
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 {
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return objectMapper.readValue(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);
return mapper.readValue(jsonString, Map.class);
}
/**
* json 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;
}
/**
* json map
*
* @param json
* @return
*/
public static Map<String, Object> json2mapDeeply(String json) throws Exception {
return json2MapRecursion(json, objectMapper);
}
/**
* json list, list jsonString,
*
* @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 value jsonString,
*
* @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
*/
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 JavaBean
*/
public static <T> T map2pojo(Map map, Class<T> clazz) {
return objectMapper.convertValue(map, clazz);
}
/**
* map json
*
* @param map
* @return
*/
public static String mapToJson(Map map) {
try {
return objectMapper.writeValueAsString(map);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* map JavaBean
*/
public static <T> T obj2pojo(Object obj, Class<T> clazz) {
return objectMapper.convertValue(obj, clazz);
}
}
해당 가방 을 가 져 오 면 사용 할 수 있 습 니 다.개인 적 으로 편리 하 다 고 생각 합 니 다!이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
초보자가 Kotlin + Spring Boot의 Get 요청에서 JSON을 반환하기 위해 한 일업무로 서버측을 하게 되었으므로 그 연습을 위해 했던 일을 정리했습니다. 서버의 경험은 한순간 밖에 없습니다 🥺🥺🥺 (Java의 입문서를 해낸 정도... 먼저 @getMapping에서 String을 반환하는 방법은 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.