[英]Create JsonObject from @ResponseBody without using gson library
@ResponseBody
返回
[{"id":1010,"name":"projectname2"}]
输入json字符串
但是我需要以下json字符串
[{"id":1010,"name":"projectname2","age":"21"}]
所以我该如何将属性属性设置为默认的json字符串呢?
我在spring-json jar中使用java spring-mvc框架
@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();
}
}
完成此操作的另一种方法(您说您现在使用的是JSONObject,而JSONObjects不是默认库)
拿绳子,
[{"id":1010,"name":"projectname2"}]
并将其转换为JSONObject。
转换后,可以使用JSONObject.append()将键“ age”附加为值“ 21”。
完成此操作的另一种方法是纯字符串操作-
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}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.