简体   繁体   中英

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;

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM