今天记录一下关于org.json.JSONObject的使用。由于项目的原因,之前我们在对外提供的sdk的过程中,为了便捷,采用了第三方com.google.gson.Gson进行json数据的解析,当初就觉得作为一个sdk提供厂商在sdk内部引入第三方的jar包不是一个稳妥的做法。现在这个问题终于暴露出来了,在给第三方提供基于apicloud平台的sdk时,由于这个gson的jar包冲突导致应用无法编译。虽然我通过模块拆分的方式解决了该问题,但是也为我提了个醒,应该尽快移除对第三方jar包的依赖。
在替换之前,就听其它人说JSONObect需要手动处理很麻烦之类的,但是由于之前通过反射处理了一些问题,因此能够立即考虑到反射的方式来解决。现在直接上三个方法的代码:
- 对象转换为json字符串
/**
* 获取对象的属性和属性值的json字符串,仅将有属性值的进行json转换
*
* @param obj
* @return
*/
public static String getJsonFromObject(Object obj) {
if (obj == null)
return null;
String json = null;
Class cla = obj.getClass();
Field[] fields = cla.getDeclaredFields();
JSONObject jsonObject = new JSONObject();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true);
String fieldName = field.getName();
Object fieldValue = null;
try {
fieldValue = field.get(obj);
if (fieldValue != null)
jsonObject.put(fieldName, fieldValue);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
field.setAccessible(false);
}
}
json = jsonObject.toString();
return json;
}
- map对象转换为json字符串
/**
* 将map转换为json字符串
* @param map map对象
* @return
*/
public static String getJsonFromMap(Map map) {
if (map == null || map.isEmpty())
return null;
String json = null;
JSONObject jsonObject = new JSONObject(map);
json = jsonObject.toString();
return json;
}
- json字符串转换为对象
/**
* 将json字符串转换为对象
* @param json json字符串
* @param classOfT 类的class对象
* @param <T>
* @return 实例化的对象
*/
public static <T> T toBean(String json, Class<T> classOfT) {
Class cla = null;
Object t = null;
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
try {
cla = Class.forName(classOfT.getName());
t = cla.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Field[] fields = cla.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true);
String fieldName = field.getName();
try {
Object value = jsonObject.get(fieldName);
if (value != null)
field.set(t, value);
} catch (JSONException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
field.setAccessible(false);
}
}
return (T) t;
}
经过测试,完全可用。可以完美地替换gson的jar包了。