You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何将HttpResponse<JsonNode>响应序列化为PostDTO对象

实现方案

前置依赖确认

首先确保项目中引入了Unirest和Jackson相关依赖,Maven配置参考如下:

<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-java</artifactId>
    <version>4.2.7</version>
</dependency>
<!-- 若使用对象映射功能需额外引入 -->
<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-object-mappers-jackson</artifactId>
    <version>4.2.7</version>
</dependency>

方案1:基于现有JsonNode返回格式转换

适合你当前已经使用asJson()获取响应的场景,核心通过Jackson的ObjectMapper完成Json到Java对象的转换:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
import java.util.List;

// 全局单例ObjectMapper,避免重复创建影响性能
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

public static PostDTO getRequest(String url, String path) throws Exception {
    HttpResponse<JsonNode> response = Unirest.get(url + path).asJson();
    // 你原代码缺少PostDTO实例化,需先创建对象
    PostDTO postDTO = new PostDTO();
    postDTO.setStatus(response.getStatus());
    
    // 核心转换逻辑:将响应体Json转为List<PostPojo>
    List<PostPojo> postList = OBJECT_MAPPER.readValue(
            response.getBody().toString(),
            new TypeReference<List<PostPojo>>() {}
    );
    postDTO.setPosts(postList);
    
    return postDTO;
}

方案2:直接使用Unirest对象映射(更推荐)

无需手动处理JsonNode,Unirest内置支持直接将响应映射为指定Java类型,代码更简洁:

import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import java.util.Arrays;
import java.util.List;

public static PostDTO getRequest(String url, String path) {
    // 直接将响应体映射为PostPojo数组
    HttpResponse<PostPojo[]> response = Unirest.get(url + path).asObject(PostPojo[].class);
    PostDTO postDTO = new PostDTO();
    postDTO.setStatus(response.getStatus());
    // 数组转List后赋值
    postDTO.setPosts(Arrays.asList(response.getBody()));
    return postDTO;
}

注意事项

  • 需确保服务端返回的JSON字段名和PostPojo类的属性名完全一致,若字段名不匹配可在对应属性上添加@JsonProperty("响应字段名")注解映射
  • 可根据业务需求捕获转换过程中的异常,添加自定义降级逻辑

内容的提问来源于stack exchange,提问作者Денис Задорожний

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:06:06