Steve
Steve

Reputation: 8819

Inject JSON file into map

I'm building a single page web app with a Spring Boot back-end and ideally want to share a JSON file that is used by the front-end as a routing enum of sorts and by the back-end to support mapping of certain routes back to /index.html

Here's the JSON file:

{
  "Login": "/login",
  "ForgotPassword": "/forgot-password",
  "ResetPassword": "/reset-password",
  "Profile": "/profile",
  "Configuration": "/configuration",
  "Administration": "/admin"
}

So far I've been doing this in Node.js as follows:

for (var pathname in Path) {
    if (Path.hasOwnProperty(pathname)) {
        app.get(Path[pathname], sendIndex);
    }
}

Currently I have this:

@Configuration
public class SpringConfigurations extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
    }
}

Would there be a way of injecting the JSON file into, let's say, a java.util.Map<String,String> and then doing the following:

@Configuration
public class SpringConfigurations extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        pathsMap.values().forEach(path -> {
            registry.addResourceHandler(path)
                    .addResourceLocations("classpath:/static/index.html");
        });
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
    }
}

Upvotes: 3

Views: 1575

Answers (1)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14383

Json Jackson library (specifically, its bind module) is able to load and parse a Json file into a Map:

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> pathsMap = (Map<String, Object>)mapper.readValue(jsonSource, Map.class);

if you know in advance that all values are Strings, you can define the map as <String, String>

readValue() has overloaded variants that accept Reader, Stream, pre-loadeded String, etc.

Upvotes: 1

Related Questions