1.需求场景
将json字符串数据反序列化为对象
2.环境
用到的包如下:
commons-beanutils-1.8.0.jar
commons-collections-3.2.1.jar
commons-lang-2.4.jar
commons-logging-1.1.3.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
3.解决方法
public class Student {
private String APPID;
private String StudentId;
//生成 getter/setter...
}
public class Teacher {
private String ret;
private String msg;
private List<Student> data;
//生成 getter/setter...
}
public class JSONTest {
/***
* 处理jackson null的问题
* @Title: filterNull
* @Description: TODO
* @param jsonObj
* @return
*/
public JSONObject filterNull(JSONObject jsonObj) {
Iterator<String> it = jsonObj.keys();
Object obj = null;
String key = null;
while (it.hasNext()) {
key = it.next();
obj = jsonObj.get(key);
if (obj instanceof JSONObject) {
filterNull((JSONObject) obj);
}
if (obj instanceof JSONArray) {
JSONArray objArr = (JSONArray) obj;
for (int i = 0; i < objArr.size(); i++) {
filterNull(objArr.getJSONObject(i));
}
}
if ((obj == null) || obj instanceof JSONNull) {
jsonObj.put(key, "");
}
if (obj.equals(null)) {
jsonObj.put(key, "");
}
}
return jsonObj;
}
public static void main(String[] args) {
JsonConfig config = new JsonConfig();
config.setRootClass(Teacher.class);
Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
classMap.put("data", Student.class);
config.setClassMap(classMap);
PropertyNameProcessor lowerCasePropertyNameProcessor = new PropertyNameProcessor() {
@Override
public String processPropertyName(Class aClass, String s) {
if (s.equals("APPID")) { //全大写不做处理
return s;
} else {
return s.substring(0, 1).toLowerCase() +
s.substring(1);
}
}
};
config.registerJavaPropertyNameProcessor(Teacher.class,
lowerCasePropertyNameProcessor);
config.registerJavaPropertyNameProcessor(Student.class,
lowerCasePropertyNameProcessor);
String data = "{\"ret\":0,\"msg\":\"Success\",\"data\":[{\"APPID\":\"10001\",\"StudentId\":\"1100\"},{\"APPID\":\"10002\",\"StudentId\":null}]}";
JSONObject json = filterNull(JSONObject.fromObject(data));
Teacher vo = (Teacher) JSONObject.toBean(json, config);
}
}