如何解决将GET请求的响应保存为类对象
我正在尝试使用针对API的GET
请求来获取一些日期。我想做的就是将此请求的响应保存为我预先创建的Java类。这是我的课:
import java.util.List;
public class Person {
String name = null;
List<Siblings> siblings = null;
}
这就是我发送GET请求并以String读取数据的方式:
try {
URL url = new URL("someURL");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization","Bearer " + "bearerString");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
InputStream content = (InputStream) connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
如何将Http请求的响应保存在类对象中而不是仅保存在字符串中?
解决方法
您可以使用Jackson
https://github.com/FasterXML/jackson
示例:
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json,Person.class);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。