Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson serialize multiple objects into one

I've got an Ajax call to populate multiple fields in the front end from Hibernate Objects. That's why I would like to return multiple Java Hibernate to Json serialized objects to Ajax from Spring. Currently I do:

  @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 to ajax but I have multiple objects like that so what I want is to nest all these objects in one json object and return the latter to my ajax so I can populate all fields using one object rather than making multiple ajax calls for each object I need. So for example I would to 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;
like image 375
george Avatar asked Jun 29 '26 07:06

george


1 Answers

You should be able to just use a Map (since JSON Objects aren't anything different than a Map) to hold 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 the objects in the Map in your JS, since the Map will get serialized as a JSON-Object:

response.someObject == { // JSON Serialization of someModelObject }
like image 92
mhlz Avatar answered Jun 30 '26 22:06

mhlz