单元测试中,@Requestbody参数的获取

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@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中。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值