将GET请求的响应保存为类对象

huangapple go评论97阅读模式
英文:

Save response of GET request as class object

问题

我正在尝试使用 GET 请求从 API 中获取一些数据。我想要做的是将此请求的响应保存为我事先创建的一个 Java 类。以下是我的类:

  1. import java.util.List;
  2. public class Person {
  3. String name = null;
  4. List<Siblings> siblings = null;
  5. }

以下是我如何发送 GET 请求并将数据读取为字符串:

  1. try {
  2. URL url = new URL("someURL");
  3. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  4. connection.setRequestMethod("GET");
  5. connection.setDoOutput(true);
  6. connection.setRequestProperty("Authorization", "Bearer " + "bearerString");
  7. connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  8. InputStream content = (InputStream) connection.getInputStream();
  9. BufferedReader in = new BufferedReader(new InputStreamReader(content));
  10. String line;
  11. while ((line = in.readLine()) != null) {
  12. System.out.println(line);
  13. }
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }

如何将 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:

  1. import java.util.List;
  2. public class Person {
  3. String name = null;
  4. List&lt;Siblings&gt; siblings = null;
  5. }

And here´s how I am sending a GET request and reading data as String:

  1. try {
  2. URL url = new URL(&quot;someURL&quot;);
  3. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  4. connection.setRequestMethod(&quot;GET&quot;);
  5. connection.setDoOutput(true);
  6. connection.setRequestProperty(&quot;Authorization&quot;, &quot;Bearer &quot; + &quot;bearerString&quot;);
  7. connection.setRequestProperty(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);
  8. InputStream content = (InputStream) connection.getInputStream();
  9. BufferedReader in = new BufferedReader(new InputStreamReader(content));
  10. String line;
  11. while ((line = in.readLine()) != null) {
  12. System.out.println(line);
  13. }
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }

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

示例:

  1. ObjectMapper mapper = new ObjectMapper();
  2. Person person = mapper.readValue(json, Person.class);
英文:

You can use Jackson https://github.com/FasterXML/jackson

Example:

  1. ObjectMapper mapper = new ObjectMapper();
  2. Person person = mapper.readValue(json, Person.class);

huangapple
  • 本文由 发表于 2020年9月8日 21:54:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63795445.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定