简体   繁体   English

将JSON对象发送到Spring控制器

[英]Sending JSON object to Spring controller

Could someone please tell me why I am getting empty body in the controller. 有人可以告诉我为什么我的控制器空了。 Here is my test 这是我的测试

 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);
    }

}

and here my controller method 这是我的控制器方法

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

I am using Spring MVC Controller Mock 我正在使用Spring MVC Controller Mock

Just try to Give datatype only String and try to convert it to the Json format at the Server side. 只需尝试仅将数据类型赋予String然后尝试在服务器端将其转换为Json format and hope that will work. 并希望能奏效。

So simple solution is Send String and convert into the JSON 如此简单的解决方案是发送String并转换为JSON

I have modified the code as follows. 我将代码修改如下。

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

I need to do a .toString() to json object and then pass to the ObjectMapper.writeValueAsString method 我需要对json对象执行.toString(),然后传递给ObjectMapper.writeValueAsString方法

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

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