@ResponseBody
返回
[{"id":1010,"name":"projectname2"}]
type json string
但是我需要一个json字符串
[{"id":1010,"name":"projectname2","age":"21"}]
那么我如何连接属性到默认生成的json字符串?
我使用java spring-mvc框架与spring-json jar
@RequestMapping(value = "/projectsByEmployeeId/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<Project> getProjectsByEmployeeId(
HttpServletRequest request) {
String filter = request.getParameter("filter");
FilterAttributes[] filterAttributes = null;
try {
filterAttributes = new ObjectMapper().readValue(filter,
FilterAttributes[].class);
} catch (Exception exception) {
logger.error("Filtering parameter JSON string passing failed",
exception);
}
if ((filterAttributes != null)
&& (!filterAttributes[0].getStringValue().isEmpty())) {
return utilityService.getProjectsByEmployeeId(44L);//this is an example id
} else {
return utilityService.getProjects();
}
}
另一种完成此操作的方法是纯字符串操作-
String json = "[{"id":1010,"name":"projectname2"}]";
json = json.substring(0, json.length() - 2); //strip the }]
String newJSON = json.concat(","age": 21}]"); // add in the new key and end
System.out.println(newJSON); // [{"id":1010,"name":"projectname2","age": 21}]
另一种方法来实现这一点(你说你正在使用JSONObject的现在,JSONObjects不是默认库)
取字符串
[{"id":1010,"name":"projectname2"}]
并将其转换为JSONObject
转换后,您可以使用JSONObject.append()将值为"21"的键"age"追加到它。