java - 如何在 Java 对象中映射 HttpResponse
问题描述
我正在通过 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
推荐阅读
- mysql - 在 Laravel 模型中加入子查询
- python - 插入本地时间戳的 Python 代码(日期 + 小时)
- c - 如何在c中动态初始化结构数组
- ethereum - 有没有办法在 Remix IDE 上进行协作?
- javascript - React Native - useEffect 将渲染 Home 两次
- c++ - C2065 's' 未声明的标识符
- java - Gradle 项目构建成功,但 IntelliJ 无法解析引用
- node.js - Stripe + Plaid 目前不适用于 .Net
- c# - C#:在没有循环的情况下访问 MultiValueDictionary 中的元素
- python - 如何使用 Django 中的提交按钮向数据库添加内容?