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

Spring Boot项目中JSON转Java对象及封装通用对象对外暴露问题

Got it, let's walk through exactly how to map your JSON response to Java objects in Spring Boot and wrap it into a reusable generic response for external consumption. Here's a clear, step-by-step breakdown:

1. Define Java Entity Classes (Matching JSON Structure)

First, we'll create nested POJOs that mirror every layer of your JSON. We'll use Lombok's @Data annotation to auto-generate getters, setters, toString, and equals/hashcode methods (you can skip Lombok and write these manually if preferred).

Policy Class (maps to the policy object)

import lombok.Data;

@Data
public class Policy {
    private String policyNumber;
    private String policyStatus;
    private Double policyPremiumAmount; // Use Integer if you're sure the value is always an integer
}

PaymentType Class (maps to items in the paymentType array)

import lombok.Data;

@Data
public class PaymentType {
    private String cardId;
    private String cardNo;
    private String cardType;
}

Pagination Class (maps to metadata.pagination)

import lombok.Data;

@Data
public class Pagination {
    private Integer offset;
    private Integer limit;
    private Integer previousOffset;
    private Integer nextOffset;
    private Integer currentPage;
    private Integer pageCount;
    private Integer totalCount;
}

Metadata Class (maps to the metadata object)

import lombok.Data;

@Data
public class Metadata {
    private Pagination pagination;
}

Root Response Class (wraps the entire JSON)

import lombok.Data;
import java.util.List;

@Data
public class PolicyResponse {
    private Policy policy;
    private List<PaymentType> paymentType;
    private Metadata metadata;
}

Note: If you don't use Lombok, add manual getters, setters, and a no-arg constructor to each class—Jackson needs these for deserialization.

2. JSON to Java Object Conversion (Using Jackson)

Spring Boot comes with Jackson out of the box, so no extra dependencies are needed. Here are two common ways to convert the JSON:

Option 1: Manual Conversion with ObjectMapper

If you have the JSON as a string (e.g., from a raw API response), use ObjectMapper to parse it:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

@Component
public class JsonParserService {
    private final ObjectMapper objectMapper;

    // Inject the auto-configured ObjectMapper from Spring
    public JsonParserService(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    public PolicyResponse parseJsonToPolicyResponse(String jsonString) throws Exception {
        return objectMapper.readValue(jsonString, PolicyResponse.class);
    }
}

Option 2: Auto-Conversion with RestTemplate

If you're calling the API directly via RestTemplate, it will automatically deserialize the response to your PolicyResponse class:

import org.springframework.web.client.RestTemplate;
import org.springframework.stereotype.Service;

@Service
public class PolicyApiClient {
    private final RestTemplate restTemplate;

    public PolicyApiClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public PolicyResponse fetchPolicyData(String apiUrl) {
        return restTemplate.getForObject(apiUrl, PolicyResponse.class);
    }
}

3. Wrap the Response in a Generic Object

To create a consistent, reusable response format for external consumers, build a generic wrapper class. This adds standard fields like status code, message, and the actual data.

Generic Response Class

import lombok.Data;

@Data
public class GenericApiResponse<T> {
    private Integer statusCode;
    private String message;
    private T data;

    // Static factory methods for easy response creation
    public static <T> GenericApiResponse<T> success(T data) {
        GenericApiResponse<T> response = new GenericApiResponse<>();
        response.setStatusCode(200);
        response.setMessage("Request successful");
        response.setData(data);
        return response;
    }

    public static <T> GenericApiResponse<T> error(Integer statusCode, String message) {
        GenericApiResponse<T> response = new GenericApiResponse<>();
        response.setStatusCode(statusCode);
        response.setMessage(message);
        response.setData(null);
        return response;
    }
}

Use the Generic Response in a Controller

Expose an endpoint that returns the wrapped policy data:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/policies")
public class PolicyController {
    private final PolicyApiClient policyApiClient;

    public PolicyController(PolicyApiClient policyApiClient) {
        this.policyApiClient = policyApiClient;
    }

    @GetMapping("/details")
    public GenericApiResponse<PolicyResponse> getPolicyDetails() {
        try {
            PolicyResponse policyData = policyApiClient.fetchPolicyData("https://your-external-api-url.com/policy");
            return GenericApiResponse.success(policyData);
        } catch (Exception e) {
            return GenericApiResponse.error(500, "Failed to retrieve policy data: " + e.getMessage());
        }
    }
}

Key Notes

  • Field Matching: Ensure Java field names exactly match JSON keys. If they differ (e.g., JSON uses policy_number), use @JsonProperty("policy_number") on the Java field to map it.
  • Type Safety: Choose numeric types carefully (Integer vs Double) based on your JSON data to avoid conversion errors.
  • Null Handling: Jackson automatically handles null values, but you can use @JsonInclude(JsonInclude.Include.NON_NULL) to exclude null fields from the response if needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:13:05