我正在使用反射来开发JsonObject转换器,但是我遇到的问题是,当我到达List<List<Object>>
之类的字段时
我正在使用批注定位要在JsonObject中写入的字段,然后使用递归方法保存和检索数据,我知道如何从List<Object>
之类的字段中获取Type,但是我需要当我检索行ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
在getValue方法中:
private Object getValue(JsonElement jsonElement, Field field, Class<?> type)
下面的方法用于返回要在参数字段上设置的值。对于单个List<Object>
字段来说,这很好用,但是我需要一种方法来获取包含在外部列表中的列表的通用类型,等等,用于所有嵌套列表。
private Object getValue(JsonElement jsonElement, Field field, Class<?> type) throws Exception {
Class<?> fieldClass = field.getType();
JsonField jsonField = field.getAnnotation(JsonField.class);
if(jsonElement instanceof JsonPrimitive) {
JsonPrimitive jsonPrimitive = (JsonPrimitive) jsonElement;
if(jsonPrimitive.isBoolean()) {
return jsonPrimitive.getAsBoolean();
}
else if(jsonPrimitive.isNumber()) {
if(type.equals(byte.class)) {
return jsonPrimitive.getAsByte();
}
else if(type.equals(short.class)) {
return jsonPrimitive.getAsShort();
}
else if(type.equals(int.class)) {
return jsonPrimitive.getAsInt();
}
else if(type.equals(long.class)) {
return jsonPrimitive.getAsLong();
}
else if(type.equals(float.class)) {
return jsonPrimitive.getAsFloat();
}
else if(type.equals(double.class)) {
return jsonPrimitive.getAsDouble();
}
else if(type.equals(Date.class)) {
return new Date(jsonPrimitive.getAsLong());
}
}
else if(jsonPrimitive.isString()) {
if(type.isEnum()) {
return Enum.valueOf(type.asSubclass(Enum.class), jsonPrimitive.getAsString());
}
else if(type.equals(UUID.class)) {
return UUID.fromString(jsonPrimitive.getAsString());
}
else {
return jsonField.stringType().load(jsonPrimitive.getAsString());
}
}
}
else if(jsonElement instanceof JsonObject) {
JsonObject jsonObject = (JsonObject) jsonElement;
Class<? extends JsonPersistent> persistent = field.getType().asSubclass(JsonPersistent.class);
return fromJson(persistent, jsonObject);
}
else if(jsonElement instanceof JsonArray) {
JsonArray jsonArray = (JsonArray) jsonElement;
//Here is were is my problem, the recursion will not work because field does not change over the recursion cycles
ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
Class<?> listClass = (Class<?>) parameterizedType.getActualTypeArguments()[0];
List<Object> list = new LinkedList<>();
for (JsonElement otherJsonElement : jsonArray) {
list.add(getValue(otherJsonElement, field, listClass));
}
return list;
}
throw new Exception("No method found to deserialize " + fieldClass.getSimpleName() + " into a field");
}