Search code examples
javarestspring-bootfasterxml

How to pass JSON from static file to rest controller SpringBoot App


I have a stable SpringBoot project that runs. I want to add a end point that reads a json file from classpath and passes it through to the response without having to create any Model objects (pass thru).

I have no issues reading the json file into JsonNode or ObjectNode, I'm struggling with where to go next to set the data in my response object.

Added this caveat later, I do need to update the json from a database.


Solution

  • Ok, paired up with a colleague at work and we tried two things, return a string (escapes strings in REST output - returns a big String.) not good. What worked is setting the response object to a and calling mapper.readValue(jsonFeed, Map.class), that returned the JSON in proper object notation.

        @Value("${metadata.json.file}") //defined in application.context
        private Resource metaJsonFileName;
    
        public String getJsonFromFile(List<UnitUiItem> uiitems){
            JsonNode root;
            ObjectMapper mapper = new ObjectMapper();
            InputStream stream = metaJsonFileName.getInputStream();
    
            root = mapper.readTree(stream);
            JsonNode dataNode = root.get("data");
            JsonNode optionDataNode = dataNode.get("storelocation");
    
            ((ObjectNode)optionDataNode).putArray("units");
           for(UnitUiItem item : uiitems){
            JsonNode unitNode = ((ObjectNode)optionDataNode).withArray("units").addObject();
            ((ObjectNode)unitNode).put("code",item.getCode());
            ((ObjectNode)unitNode).put("displayName",item.getDisplayName());
        }
    
        LOGGER.info("buildMetaJson exit");
        return root.toString();
        }
    
        //calling method
        String jsonFeed = getJsonFromFile();
        ObjectMapper mapper = new ObjectMapper();
        response.setData(mapper.readValue(jsonFeed, Map.class));
    

    I have some code cleanup to do.. any cleaner ways of doing this?