Json格式的数据现在已经算是非常通用了,大部分公司的前后端交互的数据格式首选就是json格式的数据,这个工具类JsonUtil可以满足工作中的大部分需求。
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sunvalley.hadoop.VO.ApiMsgEnum;
import com.sunvalley.hadoop.VO.BaseReturnVO;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* 类或方法的功能描述 :TODO
*
* @author: logan.zou
* @date: 2018-11-28 18:41
*/
public class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
private static final String RES_CODE = "resCode";
private static final String RES_Data = "data";
private static final String RES_DES = "resDes";
public JsonUtil() {
}
public static T fromObject(Object objs, Class type) {
try {
String json = toJSON(objs);
return fromJSON(json, type);
} catch (Exception var3) {
throw new RuntimeException(var3);
}
}
public static List fromObjectArray(Object objs, Class type) {
try {
String json = toJSON(objs);
return fromJSONArray(json, type);
} catch (Exception var3) {
throw new RuntimeException(var3);
}
}
public static T fromFeign(String json, Class type) {
try {
int resultCode = getInteger(json, "resCode");
if (resultCode != ApiMsgEnum.OK.getResCode()) {
String resDes = getString(json, "resDes");
throw new Exception(resDes);
} else {
T obj = fromJSON(json, "data", type);
return obj;
}
} catch (Exception var5) {
throw new RuntimeException(var5);
}
}
public static List fromFeignArray(String jsonStr, Class elementClass) {
try {
int resultCode = getInteger(jsonStr, "resCode");
if (resultCode != ApiMsgEnum.OK.getResCode()) {
String resDes = getString(jsonStr, "resDes");
throw new Exception(resDes);
} else {
return fromJSONArray(jsonStr, "data", elementClass);
}
} catch (Exception var4) {
throw new RuntimeException(var4);
}
}
public static List fromJSONArray(String jsonStr, String fieldName, Class elementClass) {
try {
JsonNode node = objectMapper.readTree(jsonStr);
JsonNode jsonNode = node.get(fieldName);
if (jsonNode == null) {
return null;
} else {
String fieldJson = node.get(fieldName).toString();
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, new Class[]{elementClass});
return (List)objectMapper.readValue(fieldJson, javaType);
}
} catch (Exception var7) {
throw new RuntimeException(var7);
}
}
public static List fromJSONArray(String jsonStr, Class elementClass) {
try {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, new Class[]{elementClass});
return (List)objectMapper.readValue(jsonStr, javaType);
} catch (Exception var3) {
throw new RuntimeException(var3);
}
}
public static T fromJSON(String jsonStr, String fieldName, Class elementClass) {
try {
JsonNode node = objectMapper.readTree(jsonStr);
String fieldJson = node.get(fieldName).toString();
return objectMapper.readValue(fieldJson, elementClass);
} catch (Exception var5) {
throw new RuntimeException(var5);
}
}
public static String getJsonString(String jsonStr, String fieldName) {
try {
JsonNode node = objectMapper.readTree(jsonStr);
JsonNode fieldJson = node.get(fieldName);
return fieldJson == null ? "" : node.get(fieldName).toString();
} catch (Exception var4) {
throw new RuntimeException(var4);
}
}
public static String getString(String jsonStr, String fieldName) {
try {
JsonNode node = objectMapper.readTree(jsonStr);
JsonNode fieldJson = node.get(fieldName);
return fieldJson == null ? "" : node.get(fieldName).textValue();
} catch (Exception var4) {
throw new RuntimeException(var4);
}
}
public static Integer getInteger(String jsonStr, String fieldName) {
try {
JsonNode node = objectMapper.readTree(jsonStr);
JsonNode jsonNode = node.get(fieldName);
return jsonNode == null ? null : castToInt(jsonNode.asText());
} catch (Exception var4) {
throw new RuntimeException(var4);
}
}
public static Integer getInteger(String jsonStr, String fieldName, int defVal) {
try {
JsonNode node = objectMapper.readTree(jsonStr);
JsonNode jsonNode = node.get(fieldName);
return jsonNode == null ? defVal : castToInt(jsonNode.asText());
} catch (Exception var5) {
return defVal;
}
}
public static Long getLong(String jsonStr, String fieldName) {
try {
JsonNode node = objectMapper.readTree(jsonStr);
JsonNode jsonNode = node.get(fieldName);
return jsonNode == null ? null : castToLong(jsonNode.asText());
} catch (Exception var4) {
throw new RuntimeException(var4);
}
}
public static T fromJSON(String json, Class type) {
try {
T obj = objectMapper.readValue(json, type);
return obj;
} catch (Exception var4) {
throw new RuntimeException(var4);
}
}
public static T fromJSON(BaseReturnVO baseReturnVO, Class type) {
try {
String json = toJson(baseReturnVO.getData());
T obj = objectMapper.readValue(json, type);
return obj;
} catch (Exception var4) {
throw new RuntimeException(var4);
}
}
public static T fromJSON(String source, TypeReference ref) throws Exception {
Object rtn = null;
try {
rtn = objectMapper.readValue(source, ref);
return (T) rtn;
} catch (IOException var4) {
throw var4;
}
}
public static List fromJSON(String jsonStr, Class> collectionClass, Class elementClass) throws Exception {
try {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, new Class[]{elementClass});
return (List)objectMapper.readValue(jsonStr, javaType);
} catch (Exception var4) {
throw var4;
}
}
public static String toJSON(T obj) {
try {
String jsonStr = objectMapper.writeValueAsString(obj);
return jsonStr;
} catch (Exception var3) {
throw new RuntimeException(var3);
}
}
public static String toJson(Object object) throws Exception {
return objectMapper.writeValueAsString(object);
}
private static Integer castToInt(Object value) {
if (value == null) {
return null;
} else if (value instanceof Integer) {
return (Integer)value;
} else if (value instanceof Number) {
return ((Number)value).intValue();
} else if (value instanceof String) {
String strVal = (String)value;
if (strVal.length() != 0 && !"null".equals(strVal) && !"NULL".equals(strVal)) {
if (strVal.indexOf(44) != 0) {
strVal = strVal.replaceAll(",", "");
}
return Integer.parseInt(strVal);
} else {
return null;
}
} else {
return value instanceof Boolean ? (Boolean)value ? 1 : 0 : null;
}
}
private static Long castToLong(Object value) {
if (value == null) {
return null;
} else if (value instanceof Number) {
return ((Number)value).longValue();
} else if (value instanceof String) {
String strVal = (String)value;
if (strVal.length() != 0 && !"null".equals(strVal) && !"NULL".equals(strVal)) {
if (strVal.indexOf(44) != 0) {
strVal = strVal.replaceAll(",", "");
}
try {
return Long.parseLong(strVal);
} catch (NumberFormatException var3) {
return null;
}
} else {
return null;
}
} else {
return null;
}
}
static {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
}
代码中使用到的 BaseReturnVO
public class BaseReturnVO implements Serializable {
protected int resCode;
protected String resDes;
protected Object data;
public int getResCode() {
return this.resCode;
}
public void setResCode(int resCode) {
this.resCode = resCode;
}
public String getResDes() {
return this.resDes;
}
public void setResDes(String resDes) {
this.resDes = resDes;
}
public Object getData() {
return this.data;
}
public void setData(Object data) {
this.data = data;
}
public BaseReturnVO() {
}
public BaseReturnVO(int code, String msg) {
this.resCode = code;
this.resDes = msg;
this.data = "";
}
public BaseReturnVO(int code, Exception e) {
this.resCode = code;
this.resDes = e.getMessage();
this.data = "";
}
public BaseReturnVO(int code, String msg, Exception e) {
this.resCode = code;
this.resDes = msg;
this.data = "";
}
public BaseReturnVO(Object data) {
this.resCode = ApiMsgEnum.OK.getResCode();
this.resDes = ApiMsgEnum.OK.getResDes();
this.data = data;
}
public BaseReturnVO(Exception exp) {
this.resCode = 500;
this.resDes = exp.getMessage();
this.data = "";
}
public BaseReturnVO(ApiMsgEnum msgEnum) {
this.resCode = msgEnum.getResCode();
this.resDes = msgEnum.getResDes();
this.data = "";
}
}
代码中使用到的枚举类 ApiMsgEnum
public enum ApiMsgEnum {
OK(200, "OK"),
BAD_REQUEST(400, "Bad Request"),
NOT_FOUND(404, "Not Found"),
UNAUTHORIZED(401, "Unauthorized"),
FORBIDDEN(403, "Forbidden"),
INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
BAD_GATEWAY(502, "Bad Gateway"),
SERVICE_UNAVAILABLE(503, "Service Unavailable"),
GATEWAY_TIMEOUT(504, "Gateway Timeout"),
COMMON_SERVER_ERROR(10000, "COMMON_SERVER_ERROR"),
USER_SERVER_ERROR(11000, "USER_SERVER_ERROR"),
USER_REDIS_ERROR(11001, "USER_REDIS_ERROR"),
PRODUCT_SERVER_ERROR(12000, "PRODUCT_SERVER_ERROR"),
PRODUCT_PARAMETER_ERROR(12001, "PRODUCT_PARAMETER_ERROR"),
PRODUCT_BOM_ERROR(12002, "PRODUCT_SERVER_ERROR"),
ORDER_SERVER_ERROR(13000, "ORDER_SERVER_ERROR"),
CUSTOMER_SERVER_ERROR(13000, "CUSTOMER_SERVER_ERROR");
private int resCode;
private String resDes;
public static Map apiMsgMap = new HashMap();
private ApiMsgEnum(int code, String msg) {
this.resCode = code;
this.resDes = msg;
}
private static Map getAll() {
Map retMap = new LinkedHashMap();
ApiMsgEnum[] enumArr = values();
ApiMsgEnum[] var2 = enumArr;
int var3 = enumArr.length;
for(int var4 = 0; var4 < var3; ++var4) {
ApiMsgEnum aEnum = var2[var4];
retMap.put(aEnum.getResCode(), aEnum.getResDes());
}
return retMap;
}
public int getResCode() {
return this.resCode;
}
public void setResCode(int resCode) {
this.resCode = resCode;
}
public String getResDes() {
return this.resDes;
}
public void setResDes(String resDes) {
this.resDes = resDes;
}
static {
apiMsgMap = getAll();
}
}