java - 如何解析SpringBoot中资源文件夹中的JSON
问题描述
您好我正在尝试解析我保存在资源文件夹中的 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);
}
}
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 文件时,出现错误:
error: incompatible types: Resource cannot be converted
to 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 会为您处理。而杰克逊可以直接读取 a File
,所以不需要 a 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);
}
推荐阅读
- python - 我如何确保 pytest 夹具功能只执行一次,而不管同一模块中有多少次调用
- c++ - 为什么 [[carries_dependency]] 不是 C++ 中的默认值?
- java - Groovy DSL Spring 云合约为具有 Unicode 字符的查询参数抛出 java.lang.IllegalStateException
- ios - 设置UIDatePicker preferredDatePickerStyle时为什么应用程序在iOS 14上崩溃
- python - 根据单元格在数据框中的位置选择/操作单元格
- sql-server - 如何从字符串中提取数字 5005733989
- woocommerce - 如何为 Woocommerce 查看订单模板创建简码?
- jenkins - Jenkins+AWSLoadBalancerController 示例
- python - Cassandra cqlengine python驱动程序中的聚合查询
- php - 我如何从访问 php 的最后一页获取 url?