Web服务器启动时将JSON文件转换为Java对象

时间:2019-02-05 07:28:51

标签: java json

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

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

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您可以使用@PostConstruct初始化变量:

@PostConstruct 
public void initApplication() {
    String agentName = Request.getAgentName();
    ObjectMapper mapper = new ObjectMapper();
    agent = mapper.readValue(new File(agentName), Agent.class); 
}

答案 2 :(得分:0)

我认为这些将起作用,我将在ServletContextListner类中创建一个代理类的对象,并在contextInitialized方法下,通过传递所有代理的列表来创建代理类的对象。

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ipaylabs.eme.vo.main.Agent;

public class Agents {
    private static Agents theInstance;
    private static Map<String, Agent> AGENTS_MAP;

    public Agents(String[] agentList) {
        this.AGENTS_MAP = new HashMap<>();
        for(String agentName : agentList) {
            initAgent(agentName);
        } 
    }

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


    private static void initAgent(String agentName) {
        ObjectMapper mapper = new ObjectMapper();
        Agent agent = null;
        try {
            agent = mapper.readValue(new File(agentName), Agent.class);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        AGENTS_MAP.put(agentName, agent);
    }
}