我有一个Ajax调用来从Hibernate Objects填充前端的多个字段。这就是为什么我想从Spring返回多个Java Hibernate到Json序列化对象到Ajax的原因。目前我这样做:
@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;
}
这很好,并将json对象返回给ajax但我有多个这样的对象所以我想要的是将所有这些对象嵌套在一个json对象中并将后者返回到我的ajax,这样我就可以使用一个对象填充所有字段而不是为我需要的每个对象进行多次ajax调用。例如,我想有类似的东西:
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;
答案 0 :(得分:5)
你应该能够只使用一个Map(因为JSON对象不是一个与Map不同的东西)来保存你的对象:
@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);
}
您现在可以访问JS中Map中的所有对象,因为Map将被序列化为JSON-Object:
response.someObject == { // JSON Serialization of someModelObject }