伊谢尔伦2017-04-17 16:36:22
Just use reflection to detect whether json has this field.
class A {
String a;
String b;
List<B> list;
}
class B{...}
private static void checkJson(JSONObject json, Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (!json.has(field.getName())) {
throw new JsonParseException();
}
// 遍历数组
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
Type[] types = ((ParameterizedType) type).getActualTypeArguments();
Type t = types[0];
JSONArray array = json.getJSONArray(field.getName());
for (int i = 0; i < array.length(); i++) {
Object childJSON = array.get(i);
if (childJSON instanceof JSONObject) {
checkJson((JSONObject) childJSON, (Class) t);
}
}
}
}
}
public static void main(String[] args){
A a = new A();
...
String json = new Gson().toJson(a);
checkJson(new JSONObject(json), A.class);
}
巴扎黑2017-04-17 16:36:22
It seems that it is not found. You can control it by yourself through business logic. Just make a null judgment on the Object obtained after serialization
迷茫2017-04-17 16:36:22
You can only write a custom Deserializer. You can refer to stackoverflow. Someone has asked the same question.
http://stackoverflow.com/questions/3163193/strict-json-parsing-with-googles-gson