繁体   English   中英

将JSON对象发送到Spring控制器

[英]Sending JSON object to Spring controller

有人可以告诉我为什么我的控制器空了。 这是我的测试

 public void updatePackage() throws Exception {

    JSONObject updateObj = new JSONObject();

    updateObj.append("packageType", "packageType-update-endpoint");


    SPackage updatedResponse = null;

    try {
        String json = updateObj.toString();
        System.out.println("**** JSON **** ");
        System.out.println(json + "----------" + this.response.getId());
        ResultActions result = mvcController.perform(put("/package/" + this.response.getId())
                .content(json)
                .contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk());
        updatedResponse = JsonUtil.<SPackage>convertJsonToObject(
                result.andReturn().getResponse().getContentAsString(), SPackage.class);
    } catch (Exception e) {
        e.printStackTrace();
        fail("Unexpected exception" + e);
    }

}

这是我的控制器方法

@RequestMapping(value = "/package/{id}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public SPackage updatePackage(@PathVariable String id, @RequestBody JSONObject sPackage) {
    if (sPackage == null) {
        throw new BadRequestException("Given package is null");
    }

    return softwarePackageService.updatePackage(id,sPackage);
}

我正在使用Spring MVC Controller Mock

只需尝试仅将数据类型赋予String然后尝试在服务器端将其转换为Json format 并希望能奏效。

如此简单的解决方案是发送String并转换为JSON

我将代码修改如下。

           ResultActions result = mvcController.perform(put("/package/" + this.response.getId())
            .content(new ObjectMapper().writeValueAsString(updateObj.toString()))
            .contentType(MediaType.APPLICATION_JSON))
            .andDo(print())
            .andExpect(status().isOk());

我需要对json对象执行.toString(),然后传递给ObjectMapper.writeValueAsString方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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