我有这段代码(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)时,我们得到一个哈希映射而不是Pojo Device
。
答案 0 :(得分:1)
我假设您可以通过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上写入所有条目并使测试更容易。