Search code examples
javajsonspringjacksonfasterxml

Fasterxml Jackson mapping - Data is not binding properly


I am trying to display my JSON in browser, I am getting data in JSON but getting only the last record of my table. Following jars are present in my build path,

  • jackson-databind
  • jackson-core
  • jackson-annotations

Here is my controller method

  @RequestMapping("/viewDashboard")
    @ResponseBody
    public ModelMap test(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestParam String name) {

        ModelMap modelMap = new ModelMap();
        List<Instances> instances = viewDashboardServiceImpl.viewDashboard();
        log.info(instances.size());
        return modelMap.addAllAttributes(instances);

    }
}

Actually in Database table i am five records, but in json I am getting only one record data.

In above method before adding instances list into modelMap object i am checking the size of the list and it is giving as five but in my JSON its showing only one record's data.

Here is my console output

17:08:08,638 INFO [com.mac.controller.DashboardController] (http--127.0.0.1-808 0-1) Size of Instances list: 5

Here is my JSON

{"instances":{"id":5,"instanceName":".net","applications":{"id":3,"name":">net","ownerName":"Mou","version":"3kmnc"},"environments":{"id":2,"name":"IST","ownerName":"Mou","version":"1.23.asd"},"version":"2.3as"}}

Thanks in advance.


Solution

  • It looks like the real problem here is the modelMap.addAllAttributes(instances) call. Spring will generate the keys for your list elements based on each element's classname.

    For example:

    List<String> list = Arrays.asList("x", "y", "z");
    
    ModelMap m = new ModelMap();
    m.addAllAttributes(list);
    

    Here the ModelMap will contain one entry with an attribute name "string" and a value "z". "x" and "y" will not be in the map because every generated attribute name will be "string", and the last one wins.

    To fix this, simply assign an attribute name to your instances collection when adding them to the modelMap:

    modelMap.addAttribute("myInstances", instances);