1

@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();
    }
}
4

2 に答える 2

0

これを達成する別の方法は、純粋な文字列操作です -

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}]
于 2013-06-11T13:56:51.580 に答える
0

これを達成する別の方法 (JSONObject を現在使用していて、JSONObject はデフォルトのライブラリではないと言います)

ひもを取って、

[{"id":1010,"name":"projectname2"}]

そして、それを JSONObject に変換します。

変換したら、JSONObject.append()を使用して、キー「age」と値「21」を追加できます。

于 2013-06-11T13:46:11.667 に答える