我正在尝试创建 JSON 到对象映射器。它的主要思想是“用户”定义了一个字典,其中键是 JSON 属性,值是对象属性名称。那么它是如何工作的(到目前为止):
- 从 JSON 中获取值 (var jsonValue)
- 从 getter 获取属性类型(var methodType)
- 创建setter方法并从json插入值
唯一的问题是我不能动态地将 jsonValue 转换为对象。我必须检查对象类型(methodType)是什么,然后将其转换为 String、Long、Integer 等。我可以以某种方式动态投射它吗?
private Cookbook createCookbook(JsonObject jsonCookbook) {
//Cookbook to return
Cookbook cookbook = new Cookbook();
Enumeration<String> e = mappingDictionary.keys();
while (e.hasMoreElements()) {
//get JSON value
String mappingKey = e.nextElement();
JsonElement json = jsonCookbook.get(mappingKey);
String jsonValue = json.getAsString();
//set JSON value to property
String mappingValue = mappingDictionary.get(mappingKey);
//reflection
try {
//get type of the getter
String getMethodName = "get" + mappingValue;
Method getMethod = cookbook.getClass().getMethod(getMethodName, null);
Class<?> methodType = getMethod.getReturnType();
//set methods
String setMethodName = "set" + mappingValue;
Method setMethod = cookbook.getClass().getMethod(setMethodName, methodType);
//set value to property
/* DONT WANT TO DO IT LIKE THIS, THIS IS MY PROBLEM */
if (methodType.equals(String.class))
setMethod.invoke(cookbook, jsonValue);
if (methodType.equals(Long.class))
setMethod.invoke(cookbook, Long.valueOf(jsonValue));
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return cookbook;
}