英文:
Save response of GET request as class object
问题
我正在尝试使用 GET
请求从 API 中获取一些数据。我想要做的是将此请求的响应保存为我事先创建的一个 Java 类。以下是我的类:
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 请求的响应保存到类对象中,而不仅仅是保存为字符串?
英文:
I am trying to fetch some date using a GET
request towards an API. What I want to do is to save the response of this request as a Java class I have created beforehand. Here´s my class:
import java.util.List;
public class Person {
String name = null;
List<Siblings> siblings = null;
}
And here´s how I am sending a GET request and reading data as 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();
}
How can I save the response of the Http Request in a class object instead of just a String?
答案1
得分: 1
你可以使用Jackson
,网址:https://github.com/FasterXML/jackson
示例:
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json, Person.class);
英文:
You can use Jackson
https://github.com/FasterXML/jackson
Example:
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json, Person.class);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论