且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Spring RestTemplate表示为JSON的查询参数?

更新时间:2023-11-30 23:46:58

使用 writeValueAsString 有什么问题?你可以解释吗?

What is wrong with using writeValueAsString ? Can You explain?

我想到的唯一解决方案就是(我不认为杰克逊是否有办法知道这个对象应该在那一刻被序列化) :

The only solution that comes to my mind looks like (I don't think if there is a way for Jackson to know that this object should be serialized in that moment):

@Autowired
ObjectMapper objectMapper;

@Override
public void run(String... strings) throws Exception {

    String urlBase = "http://localhost:8080/path";

    RestTemplate restTemplate = new RestTemplate();

    String url;
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.set("object", objectMapper.writeValueAsString(new MyObject()));

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(urlBase).queryParams(params);
    url = builder.build().toUri().toString();

    LOGGER.info("Composed before decode: " + url);

    //restTemplate.getForObject(url, Void.class);

    url = URLDecoder.decode(url, "UTF-8");

    LOGGER.info("Composed after decode: " + url);
}

输出:

2016-04-05 16:06:46.811  INFO 6728 --- [main] com.patrykwoj.StackOverfloApplication    : Composed before decode: http://localhost:8080/path?object=%7B%22key%22:43%7D
2016-04-05 16:06:46.941  INFO 6728 --- [main] com.patrykwoj.StackOverfloApplication    : Composed after decode: http://localhost:8080/path?object={"key":43}

编辑:

我忘了提一下,将JSON对象作为请求参数发送通常不是一个好主意。例如,您可能会遇到JSON中的大括号问题。

I forgot to mention, that sending JSON object as request parameter is generally not a good idea. For example, You will probably face problem with curly brackets inside JSON.