我正在通过 HttpClient 进行 GET REST 调用:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(endpoint))
.GET()
.header("Authorization", authHeader)
.header("Content-Type", "application/json")
.build();
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString());
如何映射 MyObject 对象中的响应?首先将其作为字符串拦截是否正确?另外,我需要传递一个字符串作为路径参数,但我不知道在哪里添加它。
感谢支持!!
最佳答案
另一个常用的库是 Jackson ObjectMapper。使用 ObjectMapper,您可以将主体映射到这样的对象:
String json = response.body(); // "{ \"name\" : \"Nemo\", \"type\" : \"Fish\" }";
Animal nemo = objectMapper.readValue(json, Animal.class);
有关分步指南,请参阅 https://www.baeldung.com/jackson-object-mapper-tutorial#2-json-to-java-object
关于java - 如何在对象 Java 中映射 HttpResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68744766/