首页 > 解决方案 > Web 服务器启动时将 JSON 文件转换为 java 对象

问题描述

我有一个 JSON 文件,我正在使用 Object Mapper 将其转换为 JAVA 对象,如下所示:-

String agentName = Request.getAgentName();
ObjectMapper mapper = new ObjectMapper();
agent = mapper.readValue(new File(agentName), Agent.class);

这些工作正常,但问题是,对于我将 json 转换为 java 对象的每个请求,我想在我的 Web 服务器启动时执行一次。我该怎么做,这是一个休息应用程序。

标签: javajson

解决方案


这可能是一个可能的解决方案,它使用带有地图的 Singleton 类,其中包含根据请求初始化的所有代理。

public class Agents {

    private static Agents theInstance;

    private final Map<String, Agent> AGENTS_MAP;

    private Agents() {
        this.AGENTS_MAP = new HashMap<>();
    }

    public static Agents getInstance() {
        if (theInstance == null) {
            theInstance = new Agents();
        }

        return theInstance;
    }

    public Agent getAgent(String agentName) {
        if (!AGENTS_MAP.containsKey(agentName) {
            initAgent(agentName);
        }

        return AGENTS_MAP.get(agentName);
    }

    // TODO handle errors
    private static void initAgent(String agentName) {
        ObjectMapper mapper = new ObjectMapper();
        Agent agent = mapper.readValue(new File(agentName), Agent.class);
        AGENTS_MAP.put(agentName, agent);
    }
}

推荐阅读