Java如何将包含对象列表的JSON反序列化为自定义Java对象
解决方案
你可以用Jackson或者Gson这类成熟的JSON序列化库完成反序列化,以下是两种常用实现方式:
方式1:使用Jackson实现
- 先引入Jackson依赖(Maven示例):
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency>
- 修改你的请求代码,直接将响应字符串反序列化为
ComData对象:
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import kong.unirest.HttpResponse; import kong.unirest.Unirest; public class Scr { public static void main(String[] args) { Unirest.config().enableCookieManagement(false); HttpResponse<String> response = Unirest.post("https://www.cse.lk/api/financials") .header("content-type", "application/x-www-form-urlencoded; charset=UTF-8") .body("symbol=DIPD.N0000") .asString(); // 反序列化核心逻辑 ObjectMapper objectMapper = new ObjectMapper(); // 忽略JSON中你没有定义的多余字段,避免反序列化报错 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); ComData comData = objectMapper.readValue(response.getBody(), ComData.class); } }
方式2:使用Gson实现
- 引入Gson依赖(Maven示例):
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> </dependency>
- 反序列化代码:
import com.google.gson.Gson; import kong.unirest.HttpResponse; import kong.unirest.Unirest; public class Scr { public static void main(String[] args) { Unirest.config().enableCookieManagement(false); HttpResponse<String> response = Unirest.post("https://www.cse.lk/api/financials") .header("content-type", "application/x-www-form-urlencoded; charset=UTF-8") .body("symbol=DIPD.N0000") .asString(); // 反序列化核心逻辑,Gson默认忽略多余字段,无需额外配置 Gson gson = new Gson(); ComData comData = gson.fromJson(response.getBody(), ComData.class); } }
注意事项
- 你定义的
FileData、InfoWebLink、ReqFinancial、InfoCompanyBannerAd这几个关联类必须提供公共无参构造方法,所有私有字段都要生成对应的getter、setter方法 - 如果Java字段名和JSON返回的键名不一致,可以用Jackson的
@JsonProperty("JSON键名")或者Gson的@SerializedName("JSON键名")注解在字段上做显式映射
内容的提问来源于stack exchange,提问作者Sathimantha Malalasekera
相关产品推荐
相关产品推荐

