我有这个代码(A):
JsonFileHandler<Device> jsonFileHandlerDevice;
final List<Device> devicesList = jsonFileHandlerDevice.getList();
和
class JsonFileHandler<T>:
@Override
public List<T> getList() {
List<T> t = null;
ObjectMapper mapper = new ObjectMapper();
if (!file.exists()) {
return null;
} else {
try {
t = mapper.readValue(file, new TypeReference<List<T>>(){});
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return t;
}
和这段代码(B):
@Override
public List<Device> getList() {
List<Device> t = null;
ObjectMapper mapper = new ObjectMapper();
if (!file.exists()) {
return null;
} else {
try {
t = mapper.readValue(file, new TypeReference<List<Device>>(){});
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return t;
}
和这个 json 文件:
[ {
"mobileOs" : "ios",
"osVersion" : 4.2,
"allocatedPort" : 0,
"hasSim" : false,
"uuid" : "uuid2",
"wazers" : [ {
"email" : null,
"emailPassword" : null,
"first" : null,
"last" : null,
"driverPhone" : null,
"riderPhone" : null,
"username" : null,
"password" : null,
"workEmail" : null,
"car" : null,
"model" : null,
"color" : null,
"plate" : null,
"obId" : null
} ],
"riders" : [ {
"email" : null,
"emailPassword" : null,
"first" : null,
"last" : null,
"driverPhone" : null,
"riderPhone" : null,
"username" : null,
"password" : null,
"workEmail" : null,
"car" : null,
"model" : null,
"color" : null,
"plate" : null,
"obId" : null
}, {
"email" : null,
"emailPassword" : null,
"first" : null,
"last" : null,
"driverPhone" : null,
"riderPhone" : null,
"username" : null,
"password" : null,
"workEmail" : null,
"car" : null,
"model" : null,
"color" : null,
"plate" : null,
"obId" : null
} ]
} ]
代码仅在执行代码 (B) 时解析 OK
并且当运行代码 (A) 时,我们得到一个 HashMap 而不是 Pojo Device
。
最佳答案
我假设您可以通过 Spring 或您用作 IoC 容器的任何方式以某种方式获得类的泛型类型,因此为简单起见,我通过构造函数传递类型。话虽这么说,我目前可以想到的一种解决方案如下:
class JsonFileHandler<T> {
private File file = new File("/Users/dambros/Desktop/test");
private final Class<T> type;
public JsonFileHandler(Class<T> type) {
this.type = type;
}
public List<T> getList() {
List<T> t;
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
if (!file.exists()) {
return null;
} else {
try {
JavaType javaType = mapper.getTypeFactory().constructParametrizedType(ArrayList.class, List.class, type);
t = mapper.readValue(file, javaType);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return t;
}
}
使用如下所示的调用将返回一个 POJO 列表而不是一个 HashMap:
JsonFileHandler<Device> jsonFileHandlerDevice = new JsonFileHandler<>(Device.class);
final List<Device> devicesList = jsonFileHandlerDevice.getList();
Obs.: 映射器配置只是为了避免必须在 JSON 上写入所有条目并使测试更容易。
关于java - 通用解析器返回 HashMap 而不是 Pojo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36284399/