【问题标题】:Save response of GET request as class object [closed]将 GET 请求的响应保存为类对象 [关闭]
【发布时间】:2020-12-26 22:19:37
【问题描述】:

我正在尝试使用对 API 的 GET 请求来获取一些日期。我想要做的是将此请求的响应保存为我事先创建的 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 请求的响应保存在一个类对象中,而不仅仅是一个字符串?

【问题讨论】:

  • 这取决于:响应格式是什么? XML? JSON?带有序列化Java对象的字节? CSV 文本?还有什么?
  • 这是 JSON,@Andreas
  • 然后使用同样支持对象映射的 JSON parser 库,例如杰克逊,格森,...
  • 这回答了你的问题:How to parse JSON in Java

标签: java get-request


【解决方案1】:

你可以使用Jacksonhttps://github.com/FasterXML/jackson

例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 2015-09-16
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    相关资源
    最近更新 更多