如何在Java中将http响应捕获为Json对象

问题描述 投票:0回答:3

我想使用CloseableHttpClient发送HTTP请求,然后在JSON对象中捕获响应的主体,以便我可以访问这样的键值:responseJson.name等

我可以使用下面的代码将响应体捕获为字符串,但是如何将其捕获为JSON对象?

CloseableHttpClient httpClient = HttpClients.createDefault();
URIBuilder builder = new URIBuilder();

    builder.setScheme("https").setHost("login.xxxxxx").setPath("/x/oauth2/token");
    URI uri = builder.build();
    HttpPost request = new HttpPost(uri);
    HttpEntity entity = MultipartEntityBuilder.create()
            .addPart("grant_type", grantType)
            .build();
    request.setEntity(entity);
    HttpResponse response = httpClient.execute(request);
    assertEquals(200, response.getStatusLine().getStatusCode());

    //This captures and prints the response as a string
    HttpEntity responseBodyentity = response.getEntity();
    String responseBodyString = EntityUtils.toString(responseBodyentity);
    System.out.println(responseBodyString);
java json apache-httpclient-4.x
3个回答
2
投票

您可以将响应字符串转换为JSON对象。

使用Jacksoncom.fasterxml.jackson.databind将字符串转换为JSON:

假设你的json-string表示如下:jsonString =“{”name“:”sample“}”

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(responseBodyString);
String phoneType = node.get("name").asText();

使用org.json库:

JSONObject jsonObj = new JSONObject(responseBodyString);
String name = jsonObj.get("name");

0
投票

只需将字符串转换为JSONObject,然后获取name的值

JSONObject obj = new JSONObject(responseBodyString);
System.out.println(obj.get("name"));

0
投票

我建议你是因为你已经将JSON作为一个字符串,编写一个利用google'Splitter'对象的方法,并定义你想要分成K-V对的字符。

例如,对于来自Spring Boot应用程序的字符串,我对K-V对做了相同的操作,并根据特殊的','字符进行拆分:

private Map<String, String> splitToMap(String in) {

    return Splitter.on(", ").withKeyValueSeparator("=").split(in);
}

替换为例如“:”,这应该将您的JSON字符串作为K-V对。

Splitter Mvn依赖性如下:

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>21.0</version>
</dependency>

希望这有助于你开始。

© www.soinside.com 2019 - 2024. All rights reserved.