Jackson serializes multiple objects into one

I have an Ajax call to populate multiple fields in a frontend from Hibernate Objects. So I would like to revert some Java Hibernate serialized Json objects to Ajax from Spring. I am currently doing:

  @RequestMapping(method=RequestMethod.GET)
  @ResponseBody
  public String getJson()
  {
     List<TableObject> result = serviceTableObject.getTableObject(pk);
     String json = "";
     ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
     try
     {
       json = ow.writeValueAsString(result);
     } catch (JsonGenerationException 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();
     }
     return json;
  }

      

This works fine and returns a json object in ajax, but I have multiple objects like what I want to nest all these objects in one json object and return the last one in my ajax so that I can fill all fields using one object instead of making multiple ajax calls for each object I need. So, for example, I would have something like:

 List<TableObject> result = serviceTableObject.getTableObject(pk);
     String json = "";
     ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
json = ow.writeValueAsString(result);


   List<SecondObject> secondObject = serviceSecondObject.getSecondObject(pk);
     String json2 = "";
     ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
json2 = ow.writeValueAsString(secondObject );

  NewJsonObject.add(json)
  NewJsonObject.add(json2)

  return newJsonObject;

      

+3


source to share


1 answer


You should be able to just use a map (since JSON objects are nothing more than a map) to store your objects:

@RequestMapping(method=RequestMethod.GET)
@ResponseBody
public String getJson() {
    Map<String, Object> theMap = new LinkedHashMap<>();
    // if you don't care about order just use a regular HashMap

    // put your objects in the Map with their names as keys
    theMap.put("someObject", someModelObject);

    // write the map using your code
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();

    return ow.writeValueAsString(theMap);
}

      



You can now access all objects in the map in your JS as the map will be serialized as JSON-Object:

response.someObject == { // JSON Serialization of someModelObject }

      

+4


source







All Articles