问题描述
我正在尝试使用针对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);