如何从Java中的Unirest响应获取原始JSON文本

时间:2018-12-12 21:23:30

标签: java json jsonpath unirest jsonparser

我正在尝试向服务器发送POST请求,获取响应,然后解析(这是一个JSON文件)。

我将Unirest用于POST请求,如下所示:

        HttpResponse<JsonNode> response = Unirest
                .post("http://myserver.com/file")
                  .header("cache-control", "no-cache")
                  .header("Postman-Token", "02ec2fa1-afdf-4a2a-a535-353424d99400")
                .header("Content-Type", "application/json")
                .body("{some JSON body}")
                .asJson();

        // retrieve the parsed JSONObject from the response
        JSONObject myObj = response.getBody().getObject();
        // extract fields from the object
        String msg = myObj.toString();

        System.out.println(msg);

但是我在获取原始JSON文本时遇到了问题(我想使用JSONPath来解析响应)。

我该怎么做?到目前为止,我所有尝试调用toString()方法的尝试都失败了。

2 个答案:

答案 0 :(得分:3)

您可以这样做:

var votevalue = $.map($(this).data('votevalue'), Number);

答案 1 :(得分:3)

Unirest API开箱即用地支持此功能-使用asString()而不是asJson()来获得HttpResponse<String>的响应。

HttpResponse<String> response = Unirest
                .post("http://myserver.com/file")
                  .header("cache-control", "no-cache")
                  .header("Postman-Token", "02ec2fa1-afdf-4a2a-a535-353424d99400")
                .header("Content-Type", "application/json")
                .body("{some JSON body}")
                .asString();
System.out.println(response.getBody());