您好,我正在尝试解析保存在资源文件夹中的 JSON 并对其进行测试。 所以我现在采取了这些步骤。
DataLoader.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);
}
}
DataLoaderTest.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);
}
}
所以当我用 //private String jsonSource = "{\"title\":\"new book\"}";
测试它时
一切正常。
当我尝试从资源文件夹加载 JSON 文件时出现错误:
错误:类型不兼容:无法转换资源
到 String JsonNode node = ApxDataLoader.parse(jsonSource);
非常感谢任何帮助。
最佳答案
使用 Spring-boot,在类路径中(例如在 resources
文件夹中)加载 json 的简单方法是:
File jsonFile = new ClassPathResource("data.json").getFile();
// or
File jsonFile = jsonResource.getFile();
JsonNode node = objectMapper.readTree(jsonFile);
无需处理 InputStream,Spring 会为您处理。并且 Jackson 可以直接读取 File
,因此也不需要 String
。
也不需要处理 JsonNode
:您还可以通过同时进行所有解析/映射来进一步优化代码的可读性:
Fruit myFruit = objectMapper.readValue(jsonFile, Fruit.class);
如果出于某种原因您仍然需要将文件内容作为字符串:
String jsonString = Files.readString(jsonFile.toPath()); // default charset of readString is UTF8
DataLoader
只能有一个方法:
public class DataLoader {
// ... objectmapper stuff ...
public static <A> A fromJason(Resource jsonResource, Class<A> clazz) throws JsonProcessingException {
return objectMapper.readValue(jsonResource.getFile(), clazz);
}
关于java - 如何解析放置在 Spring Boot 资源文件夹中的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66385253/