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

问题描述

我正在尝试使用针对API的GET请求来获取一些日期。我想做的就是将此请求的响应保存为我预先创建的Java类。这是我的课:

import java.util.List;
    
public class Person {
    String name = null;
    List<Siblings> siblings  = null;
}

这就是我发送GET请求并以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();
}

如何将Http请求的响应保存在类对象中而不是仅保存在字符串中?

解决方法

您可以使用Jackson https://github.com/FasterXML/jackson

示例:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...