如何在 Spring Webflux 中读取存储在类路径资源中的 JSON 文件?

How to read a JSON file stored in classpath resource in Spring Webflux?

我是 Spring WebFlux 的新手。我想读取存储在 classpath resource 中的 JSON 文件并转换为 POJO class。文件夹结构为 resources/defaults/myjson.json。我正在使用 Jackson 进行转换。阅读后,这将转换为 MyJson.java。截至目前,我正在执行以下方法。

@Service
public class MyService {

    private final ObjectMapper objectMapper;
    private MyJson myJson;

    @Autowired
    public MyService(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
        this.myJson = MyFileUtils.readFile(objectMapper, "classpath:/defaults/myjson.json", MyJson.class);
    }

    public MyJson getMyJson() {
        return this.myJson;
    }
}

还有其他方法吗?

您可以使用 ObjectMapper

Pojo pojo = new ObjectMapper().readValue(new ClassPathResource("./defaults/myjson.json").getFile(), Pojo.class);

这里 Pojo 定义你的 pojo class.

谢谢你提出这个问题,也感谢 gnana jeyam95 的回答对我有帮助。

我想回答你一个事实,即这将是一个阻塞 IO(我自己不知道这是不是真的)。​​

也许,如果这是个问题,您可以在应用程序启动期间一劳永逸地加载 POJO,然后始终克隆加载的 POJO(例如使用 SerializationUtils),这样您就不需要读取 JSON 文件在应用程序启动完成后不再存在。

我在我的项目中做了这样的事情:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;

@Service
public class FooServiceImpl implements FooService {
    private Pojo pojo;

    @PostConstruct
    void init() {
        try {
            pojo = new ObjectMapper().readValue(new ClassPathResource("pojo.json").getFile(), Pojo.class);
        } catch (IOException e) {
            // Log error
        }
    }

    public void myMethodNeedingPojoFromJson() {
        // Do stuff
        Pojo methodPojo = SerializationUtils.clone(pojo);
        // Do other stuff
    }
}

不过,我不知道这个优化是不是个好主意。 此外,可能有更优雅的方式来做到这一点......任何意见将不胜感激。 ^_^