@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中。
本文介绍了两种将Java对象转换为JSON字符串并将其作为请求体发送到Controller的方法。第一种方法使用ObjectMapper来序列化Java对象;第二种方法利用com.alibaba.fastjson库中的JSONObject实现相同的功能。这两种方法都需要设置正确的contentType为application/json。
1534

被折叠的 条评论
为什么被折叠?



