// 涉及jar包
jackson-core-2.6.1
jackson-databind-2.6.1
jackson-annotations-2.6.0
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.ReferenceType;
/**
* 描述:
*
* <pre>HISTORY
* ****************************************************************************
* ID DATE PERSON REASON
* 1 2018年4月9日 01371247 Create
* ****************************************************************************
* </pre>
* @author 01371247
* @since 1.0
*/
public class JSONUtils {
private static final Logger logger = LoggerFactory.getLogger(JSONUtils.class);
private JSONUtils() {
}
public static JSONObject parseJSONObject(String json) {
try {
return new JSONObject(json);
} catch (Exception e) {
logger.error("parse JSONObject error!", e);
}
return null;
}
public static JSONArray parseJSONArray(String jsonArray) {
try {
return new JSONArray(jsonArray);
} catch (Exception e) {
logger.error("parse parseJSONArray error!", e);
}
return null;
}
public static String getString(JSONObject obj, String name) {
String value = "";
try {
value = obj.getString(name);
} catch (Exception e) {
logger.error("JSONObject get String value error!", e);
}
return value;
}
public static Long getLong(JSONObject obj, String name) {
Long value = 0l;
try {
value = obj.getLong(name);
} catch (Exception e) {
logger.error("JSONObject get Long value error!", e);
}
return value;
}
public static JSONArray getJSONArray(JSONObject obj, String name) {
try {
return obj.getJSONArray(name);
} catch (Exception e) {
logger.error("JSONObject get JSONArray value error!{}", e.getMessage());
}
return null;
}
public static String toJson(Object obj) {
if (obj == null) {
return "";
}
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
logger.error("JSONUtils to String error!", e);
}
return "";
}
public static <T> T fromJson(String json, Class<T> clazz) {
ObjectMapper mapper = new ObjectMapper();
try {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.readValue(json, clazz);
} catch (IOException e) {
logger.error("JSONUtils fromJson error!", e);
}
return null;
}
public static <T> T fromJson(String json, TypeReference<T> typeReference) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(json, typeReference);
} catch (IOException e) {
logger.error("JSONUtils fromJson error!", e);
}
return null;
}