如何获取和解析来自 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);
    }

我发送了一个请求并得到了响应,按照下面的建议link:

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

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

回答:我可以从中获取JSON对象来手动解析和保存吗?或者我可以通过先前更新此 post 并添加它来获得 JSON 解析方面的帮助(answer form Postman)吗?

您可以将 ResponseEntity 视为 String。 然后你可以使用 objectMapperreadValue(),

像这样:

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

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