| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package com.uas.demo.utils;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.JavaType;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- /**
- * JSON 工具类
- *
- * history:
- * Created by huxz on 2017-3-1 10:16:03
- */
- public final class JacksonUtils {
- private static ObjectMapper objectMapper;
- /**
- * 把JSON文本parse为JavaBean
- */
- public static <T> T fromJson(String text, Class<T> clazz) {
- if (objectMapper == null) {
- objectMapper = new ObjectMapper();
- }
- try {
- return objectMapper.readValue(text, clazz);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 把JSON文本parse成JavaBean集合
- */
- public static <T> List<T> fromJsonArray(String text, Class<T> clazz) {
- if (objectMapper == null) {
- objectMapper = new ObjectMapper();
- }
- JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, clazz);
- try {
- return objectMapper.readValue(text, javaType);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return Collections.emptyList();
- }
- /**
- * 将JavaBean序列化为JSON文本
- */
- public static String toJson(Object object) {
- if (objectMapper == null) {
- objectMapper = new ObjectMapper();
- }
- try {
- return objectMapper.writeValueAsString(object);
- } catch (JsonProcessingException e) {
- e.printStackTrace();
- }
- return null;
- }
- }
|