繁体   English   中英

如何获取和解析来自 x-www-form-urlencoded POST、RestTemplate (Java) 的 JSON 响应?

[英]How to get and parse JSON response from x-www-form-urlencoded POST, RestTemplate (Java)?

我有这个方法来提出请求:

    @Override
    public HttpEntity<MultiValueMap<String, String>> generateRequestEntity(Date date) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("key", "SOME_API_KEY");
        map.add("source", "SOME_API_SOURCE");
        if (date == null)
            map.add("method", "getall");
        else {
            map.add("method", "getfrom");
            map.add("date", new SimpleDateFormat("yyyy-MM-dd").format(date));
        }

        return new HttpEntity<>(map, headers);
    }

我发送一个请求并得到一个响应,如以下链接所推荐的: URL

HttpEntity<MultiValueMap<String, String>> request = generateRequestEntity(date);
ResponseEntity<OnlineSell[]> response = restTemplate.postForEntity(url, request, OnlineSell[].class);
OnlineSell[] onlineSells = response.getBody();

但我有一个问题。 尝试解析 JSON 响应时失败。 OnlineSell - class,必须保留答案但我无法创建成功存储此答案值的结构。 一个非常大而复杂的答案树来了。

答:我可以从中获取 JSONObject 以手动解析和保存吗? 或者我可以通过之前更新这篇文章并添加它(回答表格 Postman )来获得 JSON 解析的帮助吗?

您可以做的是将 ResponseEntity 视为String 然后,您可以将objectMapperreadValue()一起使用,

像这样的东西:

ResponseEntity<String> response = restTemplate().postForEntity(url, request, String.class);

String body = response.getBody();
OnlineSell[] onlineSells = new ObjectMapper().readValue(body, OnlineSell[].class);

暂无
暂无

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

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