如何使用Spring MockMVC将JSON编码为请求参数(How to encode JSON as request parameter using Spring MockMVC)

编程入门 行业动态 更新时间:2024-10-13 08:26:05
如何使用Spring MockMVC将JSON编码为请求参数(How to encode JSON as request parameter using Spring MockMVC) java Spring

我已经尝试了几个小时将JSON编码为我正在使用Spring的MockMVC编写的测试的请求参数,但没有运气。

我的测试看起来像

@Before public void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(new TestController()) .build(); } @Test public void shouldReturnJSONGeneratedByView() throws Exception { String sampleJson = "{\"key\":\"value\"}"; String json = UriComponentsBuilder.newInstance() .path(sampleJson) .build().encode().toUriString(); mockMvc.perform(MockMvcRequestBuilders.get("/Node?json="+json)) .andExpect(status().isOk()); }

但是到达我的控制器的字符串仍然被编码(“%7B%22key%22:%22value%22%7D”),因此无法反序列化为JSON。

我想让Spring了解编码参数是什么?

谢谢你的帮助

I've been trying for a couple of hours to encode JSON as a request parameter for a test I'm writing using Spring's MockMVC but with no luck.

My test looks like

@Before public void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(new TestController()) .build(); } @Test public void shouldReturnJSONGeneratedByView() throws Exception { String sampleJson = "{\"key\":\"value\"}"; String json = UriComponentsBuilder.newInstance() .path(sampleJson) .build().encode().toUriString(); mockMvc.perform(MockMvcRequestBuilders.get("/Node?json="+json)) .andExpect(status().isOk()); }

But the String that reaches my controller is still encoded ("%7B%22key%22:%22value%22%7D") and so can't be deserialized as JSON.

What am I missing to get Spring to understand encoded parameters?

Thanks for any help

最满意答案

我相信你的JSON被编码两次,因此控制器接收一个仍然被编码的字符串(在仅被解码一次之后)。

MockMvcRequestBuilders的JavaDoc说明了第一个要get参数:

urlTemplate - 一个URL模板; 生成的URL将被编码

因此,我认为您不需要自己编码JSON,以下内容应该有效:

mockMvc.perform(MockMvcRequestBuilders.get("/Node?json={json}", sampleJson)) .andExpect(status().isOk());

I believe your JSON is being encoded twice, and therefore the controller receives a String that is still encoded (after having been decoded only once).

The JavaDoc for MockMvcRequestBuilders states the following about the first parameter to get:

urlTemplate - a URL template; the resulting URL will be encoded

Therefore I think you don't need to encode the JSON yourself, and the following should work:

mockMvc.perform(MockMvcRequestBuilders.get("/Node?json={json}", sampleJson)) .andExpect(status().isOk());

更多推荐

本文发布于:2023-08-08 00:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466634.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   参数   MockMVC   JSON   Spring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!