简体   繁体   English

如何使用Spring MockMVC将JSON编码为请求参数

[英]How to encode JSON as request parameter using Spring MockMVC

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. 我已经尝试了几个小时,将JSON编码为我正在使用Spring的MockMVC编写的测试的请求参数,但是没有运气。

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. 但是到达我的控制器的字符串仍被编码(“%7B%22key%22:%22value%22%7D”),因此不能反序列化为JSON。

What am I missing to get Spring to understand encoded parameters? 我缺少让Spring理解编码参数的东西吗?

Thanks for any help 谢谢你的帮助

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). 我相信您的JSON被编码了两次,因此控制器收到一个仍被编码的String(仅被解码一次)。

The JavaDoc for MockMvcRequestBuilders states the following about the first parameter to get : MockMvcRequestBuildersJavaDoc声明了有关要get的第一个参数的以下内容:

urlTemplate - a URL template; urlTemplate-URL模板; the resulting URL will be encoded 结果网址将被编码

Therefore I think you don't need to encode the JSON yourself, and the following should work: 因此,我认为您不需要自己对JSON进行编码,并且以下内容应该可以工作:

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

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

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