问题原因:从json文件中读取的信息为hashMap,与预期(类对象)格式不匹配,无法解析。
问题分析:json文件包含一个json串列表,代表向接口中传递不同的参数组合,通过下面方法读取json文件信息,反序列化成类对象,并把这些赋值的对象进行接口请求参数进行传递。
public List<T> getReadValuesList(String pathUrl){
try {
if(pathUrl.endsWith("json")){
objectMapper = new ObjectMapper(new JsonFactory());
}else if(pathUrl.endsWith("yaml") | pathUrl.endsWith("yml")){
objectMapper = new ObjectMapper(new YAMLFactory());
}
TypeReference<List<T>> reference = new TypeReference<List<T>>() {};
readValueList = objectMapper.readValue(new File(pathUrl), reference);
} catch (IOException e) {
throw new RuntimeException(e);
}
readValueList.forEach(readValues -> {
System.out.println(readValues.toString());
});
return readValueList;
}
解决方法:
1 、类对象添加implements Serializable
2、json文件读取方法添加预制类型参数,如下:
public List<T> getReadValuesList(String pathUrl, TypeReference<List<T>> typeR){
try {
if(pathUrl.endsWith("json")){
objectMapper = new ObjectMapper(new JsonFactory());
}else if(pathUrl.endsWith("yaml") | pathUrl.endsWith("yml")){
objectMapper = new ObjectMapper(new YAMLFactory());
}
readValueList = objectMapper.readValue(new File(pathUrl), typeR);
} catch (IOException e) {
throw new RuntimeException(e);
}
readValueList.forEach(readValues -> {
System.out.println(readValues.toString());
});
return readValueList;
}
3、方法调用:
PS:知识加油站:
1、在实现接口自动化的过程中,读取接口请求数据的其中一个方法是json文件的读取,经常会把读取json文件的内容写作一个公共的方法;
2、java类名后面加尖括号是指如果使用某个类的对象作为参数或返回值时,可以将该类放入尖括号内,这种写法称为“泛型”;
3、类对象打印的样式为:对象名(字段=值,字段=值......);
hashmap打印的样式为:{字段=值,字段=值......}
4、待加强知识点为:泛型 (https://www.bilibili.com/video/BV1Nx4y1Q7uM/?spm_id_from=333.788&vd_source=defc65f9acbd5f4f8cbca5cf1fa93ee0)
标签:lang,java,读取,....,json,readValueList,pathUrl,new,objectMapper From: https://www.cnblogs.com/momoyou/p/18051765