首页 > 解决方案 > 如何解析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);

任何帮助高度赞赏。

标签: javaspring-boottesting

解决方案


使用 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);
  }

推荐阅读