@Requestbody参数,即发送一个Json参数到Controller层
解决方法一:
ObjectMapper mapper = new ObjectMapper(); ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); java.lang.String requestJson = ow.writeValueAsString(userFeedbackModel); String responseString = mockMvc.perform( MockMvcRequestBuilders.post("/userFeedback/saveUserFeedback.api") .contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andReturn().getResponse().getContentAsString();
解决方法2:使用com.alibaba.fastjson.JSONObject将对象转换为Json数据
String requestJson = JSONObject.toJSONString(userFeedbackModel); String responseString = mockMvc.perform(MockMvcRequestBuilders.post("/userFeedback/saveUserFeedback.api") .contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andReturn().getResponse().getContentAsString();
注意上面contentType需要设置成MediaType.APPLICATION_JSON,即声明是发送“application/json”格式的数据。使用content方法,将转换的json数据放到request的body中。