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

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

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&lt;Siblings&gt; siblings  = null;
}

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

try {
    URL url = new URL(&quot;someURL&quot;);
    
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(&quot;GET&quot;);
    connection.setDoOutput(true);
    connection.setRequestProperty(&quot;Authorization&quot;, &quot;Bearer &quot; + &quot;bearerString&quot;);
    connection.setRequestProperty(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);

    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);

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:

确定