use*_*049 4 java testing spring-boot
您好,我正在尝试解析我保存在资源文件夹中的 JSON 并对其进行测试。所以我现在采取了这些步骤。
数据加载器.java
@Service
public class DataLoader {
private static ObjectMapper objectMapper = defaultObjectMapper();
private static ObjectMapper defaultObjectMapper(){
ObjectMapper defaultObjectMapper = new ObjectMapper();
//defaultObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return defaultObjectMapper;
}
public static JsonNode parse(String str) throws IOException {
return objectMapper.readTree(str);
}
public static <A> A fromJason(JsonNode node, Class<A> clazz) throws JsonProcessingException {
return objectMapper.treeToValue(node, clazz);
}
}
Run Code Online (Sandbox Code Playgroud)
数据加载器测试.java
public class DataLoaderTest {
@Value("classpath:data/novo.json")
Resource jsonSource;
//private String jsonSource = "{\"title\":\"new book\"}";
@Test
public void parse() throws IOException {
JsonNode node = DataLoader.parse(jsonSource);
assertEquals(node.get("title").asText(), "new book");
}
@Test
public void fromJson() throws IOException {
JsonNode node = DataLoader.parse(jsonSource);
Fruit pojo = DataLoader.fromJason(node, Fruit.class);
System.out.println("Pojo title " + pojo.title);
}
}
Run Code Online (Sandbox Code Playgroud)
所以当我测试它时 //private String jsonSource = "{\"title\":\"new book\"}";
一切都工作正常。
当我尝试从资源文件夹加载 JSON 文件时,出现错误:
error: incompatible types: Resource cannot be converted
to String JsonNode node = ApxDataLoader.parse(jsonSource);
非常感谢任何帮助。
小智 8
使用 Spring-boot,在类路径(例如文件夹中resources)加载 json 的简单方法是:
File jsonFile = new ClassPathResource("data.json").getFile();
// or
File jsonFile = jsonResource.getFile();
JsonNode node = objectMapper.readTree(jsonFile);
Run Code Online (Sandbox Code Playgroud)
无需处理InputStream,Spring 会为您处理好。杰克逊可以直接阅读File,所以两者都不需要String。
两者都不需要处理JsonNode:您还可以通过同时执行所有解析/映射来进一步优化代码的可读性:
Fruit myFruit = objectMapper.readValue(jsonFile, Fruit.class);
Run Code Online (Sandbox Code Playgroud)
如果出于某种原因您仍然需要文件内容作为字符串:
String jsonString = Files.readString(jsonFile.toPath()); // default charset of readString is UTF8
Run Code Online (Sandbox Code Playgroud)
DataLoader只能有一种方法:
public class DataLoader {
// ... objectmapper stuff ...
public static <A> A fromJason(Resource jsonResource, Class<A> clazz) throws JsonProcessingException {
return objectMapper.readValue(jsonResource.getFile(), clazz);
}
Run Code Online (Sandbox Code Playgroud)