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

使用RestTemplate和Jackson将JSON响应反序列化为Java对象遇问题

解决Spring Boot 1.5中Jackson反序列化嵌套JSON数组的问题

我来帮你搞定这个Jackson反序列化的难题!首先咱们先把你的JSON结构拆解清楚:外层是一个数组,数组里只有一个对象,这个对象包含两个核心属性——deploymentProject(嵌套对象)和environmentStatuses(另一个数组,每个元素是包含environment和deploymentResult的嵌套对象)。接下来咱们一步步实现反序列化:

1. 匹配JSON结构创建Java实体类

从最内层的对象开始定义,每个类对应JSON里的嵌套结构,同时添加@JsonIgnoreProperties(ignoreUnknown = true)来忽略JSON中可能存在的未定义字段(比如你JSON里的{...}部分),避免反序列化时抛出异常。

1.1 定义DeploymentProject类(对应deploymentProject对象)

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class DeploymentProject {
    @JsonProperty("id")
    private Long id;
    
    @JsonProperty("name")
    private String name;

    // 生成getter、setter方法,或者用Lombok的@Data注解(项目引入Lombok的话更简洁)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

1.2 定义Environment类(对应environment对象)

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Environment {
    @JsonProperty("id")
    private Long id;
    
    @JsonProperty("name")
    private String name;
    
    @JsonProperty("deploymentProjectId")
    private Long deploymentProjectId;

    // getter和setter方法
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getDeploymentProjectId() {
        return deploymentProjectId;
    }

    public void setDeploymentProjectId(Long deploymentProjectId) {
        this.deploymentProjectId = deploymentProjectId;
    }
}

1.3 定义DeploymentResult类(对应deploymentResult对象)

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class DeploymentResult {
    @JsonProperty("deploymentVersionName")
    private String deploymentVersionName;
    
    @JsonProperty("id")
    private Long id;

    // getter和setter方法
    public String getDeploymentVersionName() {
        return deploymentVersionName;
    }

    public void setDeploymentVersionName(String deploymentVersionName) {
        this.deploymentVersionName = deploymentVersionName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

1.4 定义EnvironmentStatus类(对应environmentStatuses数组的元素)

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class EnvironmentStatus {
    @JsonProperty("environment")
    private Environment environment;
    
    @JsonProperty("deploymentResult")
    private DeploymentResult deploymentResult;

    // getter和setter方法
    public Environment getEnvironment() {
        return environment;
    }

    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    public DeploymentResult getDeploymentResult() {
        return deploymentResult;
    }

    public void setDeploymentResult(DeploymentResult deploymentResult) {
        this.deploymentResult = deploymentResult;
    }
}

1.5 定义顶层DeploymentResponse类(对应数组内的单个对象)

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
public class DeploymentResponse {
    @JsonProperty("deploymentProject")
    private DeploymentProject deploymentProject;
    
    @JsonProperty("environmentStatuses")
    private List<EnvironmentStatus> environmentStatuses;

    // getter和setter方法
    public DeploymentProject getDeploymentProject() {
        return deploymentProject;
    }

    public void setDeploymentProject(DeploymentProject deploymentProject) {
        this.deploymentProject = deploymentProject;
    }

    public List<EnvironmentStatus> getEnvironmentStatuses() {
        return environmentStatuses;
    }

    public void setEnvironmentStatuses(List<EnvironmentStatus> environmentStatuses) {
        this.environmentStatuses = environmentStatuses;
    }
}

2. 反序列化代码实现

在Spring Boot 1.5中,你可以选择手动用ObjectMapper反序列化,或者通过RestTemplate调用接口时自动完成反序列化。

2.1 手动使用ObjectMapper反序列化

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;

public class DeserializationDemo {
    public static void main(String[] args) throws Exception {
        // 你的JSON字符串
        String json = "[ { \"deploymentProject\": { \"id\": 57966596, \"name\": \"MyApp 6.3\" }, \"environmentStatuses\": [{ \"environment\": { \"id\": 57245736, \"name\": \"Dev1\", \"deploymentProjectId\": 57966596 }, \"deploymentResult\": { \"deploymentVersionName\": \"App-51\", \"id\": 59769040 } }, { \"environment\": {} } ] } ]";
        
        ObjectMapper objectMapper = new ObjectMapper();
        // 反序列化为List<DeploymentResponse>,因为外层是数组
        List<DeploymentResponse> responses = objectMapper.readValue(json, 
            objectMapper.getTypeFactory().constructCollectionType(List.class, DeploymentResponse.class));
        
        // 取数组中的第一个对象(你的JSON里只有一个)
        DeploymentResponse response = responses.get(0);
        // 测试获取嵌套属性
        System.out.println("项目名称:" + response.getDeploymentProject().getName());
        System.out.println("第一个环境名称:" + response.getEnvironmentStatuses().get(0).getEnvironment().getName());
    }
}

2.2 使用RestTemplate自动反序列化

如果是调用外部接口获取JSON,可以直接让RestTemplate帮你完成转换:

import org.springframework.web.client.RestTemplate;
import org.springframework.core.ParameterizedTypeReference;
import java.util.List;

@Service
public class DeploymentService {
    private final RestTemplate restTemplate;

    // 构造注入RestTemplate(Spring Boot 1.5默认支持)
    public DeploymentService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public DeploymentResponse fetchDeploymentInfo() {
        String apiUrl = "你的目标接口URL";
        // 指定返回类型为List<DeploymentResponse>
        List<DeploymentResponse> responses = restTemplate.exchange(
            apiUrl,
            org.springframework.http.HttpMethod.GET,
            null,
            new ParameterizedTypeReference<List<DeploymentResponse>>() {}
        ).getBody();
        return responses.get(0);
    }
}

注意事项

  • Spring Boot 1.5的spring-boot-starter-web依赖已经包含了Jackson相关组件,无需额外引入。
  • 如果Java字段名和JSON键名完全一致,可以省略@JsonProperty注解,但加上后代码可读性更强,也能避免字段名修改引发的问题。
  • @JsonIgnoreProperties(ignoreUnknown = true)一定要加,否则JSON中未定义的字段会导致反序列化失败。

内容的提问来源于stack exchange,提问作者user6605797

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:31:14