json处理类
市面上用于在 Java 中解析 Json 的第三方库,随便一搜不下几十种,其中的佼佼者有 Google 的 Gson, Alibaba 的 Fastjson 以及本文的 jackson。
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<!-- 如可以使用最新的 2.9.7、2.9.8 版本 -->
<version>${jackson.version.core}</version>
</dependency>
package com.cmsz.paydemo.util;
import java.io.IOException;
import java.io.StringWriter;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* {@code JsonUtil}主要区分普通类型和泛型两种。
* <p>
* 提供将类(包括泛型)与json字符串互转的方法;
* <p>
* 从json字符串内部提取出内部的bean的方法;
* <p>
* 更新json字符串内部bean字符串的方法。
*
* @author liyuanchang, wuhang
*
*/
public class JsonUtil {
private static ThreadLocal<ObjectMapper> local = new ThreadLocal<ObjectMapper>() {
@Override
protected ObjectMapper initialValue() {
return new ObjectMapper();
}
};
/**
* 将JavaBean将转换为Json字符串
*
* @param obj
* - java对象
* @return
* @throws JsonProcessingException
*/
public static String object2JsonStr(Object obj) throws JsonProcessingException {
ObjectMapper mapper = local.get();
String jsonStr;
try {
jsonStr = mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw e;
}
return jsonStr;
}
/**
* 将JSON格式的字符串转为JavaBean
*
* @param json
* @param clazz
* @return
* @throws IOException
* @throws JsonParseException
* - json格式出错
* @throws JsonMappingException
* - 类型有问题
*/
public static <T> T jsonStr2Obj(String json, Class<T> clazz) throws IOException {
ObjectMapper mapper = local.get();
T obj;
try {
obj = mapper.readValue(json, clazz);
} catch (JsonParseException e) {
throw e;
}catch (JsonMappingException e){
throw e;
}catch (IOException e) {
throw e;
}
return obj;
}
/**
* 从 json里获取内部bean
*
* @param json
* json字符串
* @param fieldName
* 属性名
* @param clazz
* @return
* @throws IOException
*/
public static <T> T get(String json, String fieldName, Class<T> clazz) throws IOException {
ObjectMapper mapper = local.get();
T obj;
try {
ObjectNode objectNode = (ObjectNode) mapper.readTree(json);
obj = mapper.readValue(objectNode.get(fieldName).toString(), clazz);
} catch (JsonParseException e) {
throw e;
} catch (JsonMappingException e){
throw e;
}
catch (IOException e) {
throw e;
}
return obj;
}
/**
* 从 json里获取内部bean
*
* @param json
* json字符串
* @param fieldName
* 属性名
* @param valueTypeRef
* 类型,eg:new TypeReference<List<ChargeQueryBean>>(){}
* @param clazz
* @return
* @throws IOException
*/
public static <T> T get(String json, String fieldName, TypeReference<?> valueTypeRef) throws IOException {
ObjectMapper mapper = local.get();
T obj;
try {
ObjectNode objectNode = (ObjectNode) mapper.readTree(json);
obj = mapper.readValue(objectNode.get(fieldName).toString(), valueTypeRef);
} catch (JsonParseException e) {
throw e;
}catch (JsonMappingException e){
throw e;
}
catch (IOException e) {
throw e;
}
return obj;
}
/**
* 将新json字符串更新到json字符串中
*
* @param json
* 原json字符串
* @param needToUpdate
* 新字符串
* @param fieldName
* 属性名
* @return
* @throws IOException
*/
public static String updateJsonStr(String json, String needToUpdate, String fieldName) throws IOException {
ObjectMapper mapper = local.get();
ObjectNode objectNode = null;
try {
JsonNode needToUpdateNode = null;
objectNode = (ObjectNode) mapper.readTree(json);
needToUpdateNode = mapper.readTree(needToUpdate);
objectNode.set(fieldName, needToUpdateNode);
json = objectNode.toString();
return json;
} catch (IOException e) {
throw e;
}
}
/**
* 将Bean转为带有泛型的对象<br>
* 使用示例 List<ChrageQueryBean> list =
* JsonUtil.jsonStr2GenericObj(jsonStr, new
* TypeReference<List<ChrageQueryBean>>() {});
*
* @param json
* - json字符串
* @param type
* - jackson中定义的TypeReference对象
* @return
* @throws IOException
*/
public static <T> T jsonStr2GenericObj(String json, TypeReference<?> type) throws IOException {
ObjectMapper mapper = local.get();
T genericObj;
try {
genericObj = mapper.readValue(json, type);
} catch (JsonParseException e) {
throw e;
}catch (JsonMappingException e){
throw e;
} catch (IOException e) {
throw e;
}
return genericObj;
}
/**
* 将泛型Bean转为Json字符串,并保留特殊设置<br>
* 使用示例 String jsonStr = JsonUtil.genericObj2JsonStr(list, new
* TypeReference<List<XPayBean>>() {});
*
* @param obj
* - java对象
* @param type
* - jackson中定义的TypeReference对象
* @return
* @throws IOException
*/
public static <T> String genericObj2JsonStr(T obj, TypeReference<?> type) throws IOException {
ObjectMapper mapper = local.get();
ObjectWriter writer = mapper.writerFor(type);
StringWriter w = new StringWriter();
try {
writer.writeValue(w, obj);
} catch (JsonParseException e) {
throw e;
}catch (JsonMappingException e){
throw e;
} catch (IOException e) {
throw e;
}
return w.toString();
}
}
工具二、
package com.xxx.xxx.util.xxx;
import java.io.IOException;
import java.io.StringWriter;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* {@code JsonUtil}主要区分普??类型和泛型两种??
* <p>
* 提供将类(包括泛型)与json字符串互转的方法??
* <p>
* 从json字符串内部提取出内部的bean的方法;
* <p>
* 更新json字符串内部bean字符串的方法??
*
*
*/
public class JsonUtil {
private static ThreadLocal<ObjectMapper> local = new ThreadLocal<ObjectMapper>() {
@Override
protected ObjectMapper initialValue() {
return new ObjectMapper();
}
};
/**
* 将JavaBean将转换为Json字符??
*
* @param obj
* - java对象
* @return
* @throws JsonProcessingException
*/
public static String object2JsonStr(Object obj) throws JsonProcessingException {
ObjectMapper mapper = local.get();
String jsonStr;
try {
jsonStr = mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw e;
}
return jsonStr;
}
/**
* 将JSON格式的字符串转为JavaBean
*
* @param json
* @param clazz
* @return
* @throws IOException
* @throws JsonParseException
* - json格式出错
* @throws JsonMappingException
* - 类型有问??
*/
public static <T> T jsonStr2Obj(String json, Class<T> clazz) throws IOException {
ObjectMapper mapper = local.get();
T obj;
try {
obj = mapper.readValue(json, clazz);
} catch (JsonParseException e) {
throw e;
}catch (JsonMappingException e){
throw e;
}catch (IOException e) {
throw e;
}
return obj;
}
/**
* ??json里获取内部bean
*
* @param json
* json字符??
* @param fieldName
* 属????
* @param clazz
* @return
* @throws IOException
*/
public static <T> T get(String json, String fieldName, Class<T> clazz) throws IOException {
ObjectMapper mapper = local.get();
T obj;
try {
ObjectNode objectNode = (ObjectNode) mapper.readTree(json);
obj = mapper.readValue(objectNode.get(fieldName).toString(), clazz);
} catch (JsonParseException e) {
throw e;
} catch (JsonMappingException e){
throw e;
}
catch (IOException e) {
throw e;
}
return obj;
}
/**
* ??json里获取内部bean
*
* @param json
* json字符??
* @param fieldName
* 属????
* @param valueTypeRef
* 类型,eg:new TypeReference<List<ChargeQueryBean>>(){}
* @param
* @return
* @throws IOException
*/
public static <T> T get(String json, String fieldName, TypeReference<?> valueTypeRef) throws IOException {
ObjectMapper mapper = local.get();
T obj;
try {
ObjectNode objectNode = (ObjectNode) mapper.readTree(json);
obj = mapper.readValue(objectNode.get(fieldName).toString(), valueTypeRef);
} catch (JsonParseException e) {
throw e;
}catch (JsonMappingException e){
throw e;
}
catch (IOException e) {
throw e;
}
return obj;
}
/**
* 将新json字符串更新到json字符串中
*
* @param json
* 原json字符??
* @param needToUpdate
* 新字符串
* @param fieldName
* 属????
* @return
* @throws IOException
*/
public static String updateJsonStr(String json, String needToUpdate, String fieldName) throws IOException {
ObjectMapper mapper = local.get();
ObjectNode objectNode = null;
try {
JsonNode needToUpdateNode = null;
objectNode = (ObjectNode) mapper.readTree(json);
needToUpdateNode = mapper.readTree(needToUpdate);
objectNode.set(fieldName, needToUpdateNode);
json = objectNode.toString();
return json;
} catch (IOException e) {
throw e;
}
}
/**
* 将Bean转为带有泛型的对??br>
* 使用示例 List<ChrageQueryBean> list =
* JsonUtil.jsonStr2GenericObj(jsonStr, new
* TypeReference<List<ChrageQueryBean>>() {});
*
* @param json
* - json字符??
* @param type
* - jackson中定义的TypeReference对象
* @return
* @throws IOException
*/
public static <T> T jsonStr2GenericObj(String json, TypeReference<?> type) throws IOException {
ObjectMapper mapper = local.get();
T genericObj;
try {
genericObj = mapper.readValue(json, type);
} catch (JsonParseException e) {
throw e;
}catch (JsonMappingException e){
throw e;
} catch (IOException e) {
throw e;
}
return genericObj;
}
/**
* 将泛型Bean转为Json字符串,并保留特殊设??br>
* 使用示例 String jsonStr = JsonUtil.genericObj2JsonStr(list, new
* TypeReference<List<XPayBean>>() {});
*
* @param obj
* - java对象
* @param type
* - jackson中定义的TypeReference对象
* @return
* @throws IOException
*/
public static <T> String genericObj2JsonStr(T obj, TypeReference<?> type) throws IOException {
ObjectMapper mapper = local.get();
ObjectWriter writer = mapper.writerFor(type);
StringWriter w = new StringWriter();
try {
writer.writeValue(w, obj);
} catch (JsonParseException e) {
throw e;
}catch (JsonMappingException e){
throw e;
} catch (IOException e) {
throw e;
}
return w.toString();
}
}
工具三
package com.xxxx.aipay.common.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
/**
* <p>Title: Json转换工具</p>
* <p>Description: 提供Json报文与Map对象互相转换的相关方法</p>
*/
public class JsonUtil {
/**
* 将Map、List、JavaBean、数组等对象格化成Json字符串
* @param object 对象
* @return String Json字符串
* @throws Exception
*/
public static String format(Object object) throws Exception {
String str = null;
if (object != null) {
try {
if (object instanceof List || object instanceof Object[]) {
JSONArray json = JSONArray.fromObject(object);
str = json.toString();
} else {
JSONObject json = JSONObject.fromObject(object);
str = json.toString();
}
} catch (Exception e) {
throw new Exception("不支持的对象类型(" + object.getClass().getName() + ").");
}
}
return str;
}
/**
* 将Json格式的字符串解析成Map对象
* @param str Json字符串
* @return Map Map对象
* @throws Exception
*/
public static Object parse(String str) throws Exception {
Object object = null;
if (StringUtils.isNotBlank(str)) {
if (str.startsWith("{") && str.endsWith("}")) {
JSONObject json = JSONObject.fromObject(str);
object = parse(json);
} else {
JSONArray jsonarry = JSONArray.fromObject(str);
object = parse(jsonarry);
}
}
return object;
}
/**
* 将Json对象解析成Map对象
* @param str Json字符串
* @return Map Map对象
* @throws Exception
*/
private static Map parse(JSONObject json) throws Exception {
Map map = null;
if (json != null) {
map = new HashMap();
Iterator iterator = json.keys();
while (iterator.hasNext()) {
Object key = iterator.next();
Object value = json.get(key.toString());
if (value instanceof JSONObject) {
value = parse((JSONObject)value);
} else if (value instanceof JSONArray) {
value = parse((JSONArray)value);
}
map.put(key, value);
}
}
return map;
}
/**
* 将Json数组对象解析成对象数组
* @param str Json字符串
* @return Map Map对象
* @throws Exception
*/
private static Object[] parse(JSONArray jsonarry) throws Exception {
Object[] objects = null;
if (jsonarry != null) {
List list = new ArrayList();
Iterator iter = ((JSONArray)jsonarry).iterator();
while (iter.hasNext()) {
Object value = iter.next();
if (value instanceof JSONObject) {
value = parse((JSONObject)value);
} else if (value instanceof JSONArray) {
value = parse((JSONArray)value);
}
list.add(value);
}
objects = list.toArray();
}
return objects;
}
}
参考:
https://blog.csdn.net/wangmx1993328/article/details/88598625