将 GET 请求的响应保存为 class 对象
Save response of GET request as class object
我正在尝试使用 API 的 GET
请求获取一些日期。我想要做的是将此请求的响应保存为我事先创建的 Java class。这是我的 class:
import java.util.List;
public class Person {
String name = null;
List<Siblings> siblings = null;
}
下面是我发送 GET 请求并将数据读取为字符串的方式:
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 请求的响应保存在 class 对象中,而不仅仅是一个字符串?
您可以使用 Jackson
https://github.com/FasterXML/jackson
示例:
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json, Person.class);
我正在尝试使用 API 的 GET
请求获取一些日期。我想要做的是将此请求的响应保存为我事先创建的 Java class。这是我的 class:
import java.util.List;
public class Person {
String name = null;
List<Siblings> siblings = null;
}
下面是我发送 GET 请求并将数据读取为字符串的方式:
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 请求的响应保存在 class 对象中,而不仅仅是一个字符串?
您可以使用 Jackson
https://github.com/FasterXML/jackson
示例:
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json, Person.class);