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

使用Java验证JSON响应并提取taxType与taxAmount字段

Java JSON Validation & Field Extraction (taxType/taxAmount)

Let's break down how to validate your JSON response and extract the required taxType and taxAmount fields using Java. We'll use Jackson Databind (one of the most popular JSON processing libraries for Java) since it simplifies both mapping and validation.

Step 1: Add Jackson Dependency

First, include the Jackson Databind dependency in your project. If you're using Maven, add this to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Use the latest stable version -->
</dependency>

For Gradle:

implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'

Step 2: Create POJO Classes to Map the JSON Structure

We'll create plain old Java objects that mirror the structure of your JSON response. This makes validation and field extraction straightforward.

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

// Root class for the JSON response
@JsonIgnoreProperties(ignoreUnknown = true) // Ignore fields we don't need
public class InvoiceResponse {
    private boolean taxExempt;
    private BillingAddress billingAddress;
    private String date;
    private double totalTax;
    private List<Item> items;

    // Getters and Setters
    public boolean isTaxExempt() { return taxExempt; }
    public void setTaxExempt(boolean taxExempt) { this.taxExempt = taxExempt; }
    public BillingAddress getBillingAddress() { return billingAddress; }
    public void setBillingAddress(BillingAddress billingAddress) { this.billingAddress = billingAddress; }
    public String getDate() { return date; }
    public void setDate(String date) { this.date = date; }
    public double getTotalTax() { return totalTax; }
    public void setTotalTax(double totalTax) { this.totalTax = totalTax; }
    public List<Item> getItems() { return items; }
    public void setItems(List<Item> items) { this.items = items; }
}

// Billing Address nested class
@JsonIgnoreProperties(ignoreUnknown = true)
class BillingAddress {
    private String addressLine1;
    private String city;
    private String postalCode;

    // Getters and Setters
    public String getAddressLine1() { return addressLine1; }
    public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; }
    public String getCity() { return city; }
    public void setCity(String city) { this.city = city; }
    public String getPostalCode() { return postalCode; }
    public void setPostalCode(String postalCode) { this.postalCode = postalCode; }
}

// Item nested class
@JsonIgnoreProperties(ignoreUnknown = true)
class Item {
    private List<Tax> taxes;

    // Getters and Setters
    public List<Tax> getTaxes() { return taxes; }
    public void setTaxes(List<Tax> taxes) { this.taxes = taxes; }
}

// Tax nested class (contains our target fields)
@JsonIgnoreProperties(ignoreUnknown = true)
class Tax {
    private String taxType;
    private Double taxAmount; // Use Double to handle nulls if the field might be missing

    // Getters and Setters
    public String getTaxType() { return taxType; }
    public void setTaxType(String taxType) { this.taxType = taxType; }
    public Double getTaxAmount() { return taxAmount; }
    public void setTaxAmount(Double taxAmount) { this.taxAmount = taxAmount; }
}

Step 3: Implement JSON Validation

We'll validate critical fields to ensure the JSON response meets expected standards (e.g., required fields exist, correct data types, valid date format).

import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class JsonProcessor {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static InvoiceResponse validateAndParseJson(String jsonResponse) throws Exception {
        // Parse JSON to POJO (basic validation: checks for correct data types)
        InvoiceResponse response = objectMapper.readValue(jsonResponse, InvoiceResponse.class);

        // Validate required fields exist and are valid
        if (response.getBillingAddress() == null || response.getBillingAddress().getAddressLine1().isEmpty()) {
            throw new IllegalArgumentException("Billing address line 1 is required");
        }

        if (response.getDate() == null) {
            throw new IllegalArgumentException("Invoice date is required");
        }

        // Validate date format (yyyy-MM-dd)
        try {
            LocalDate.parse(response.getDate(), DATE_FORMATTER);
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("Invalid date format. Expected yyyy-MM-dd");
        }

        if (response.getItems() == null || response.getItems().isEmpty()) {
            throw new IllegalArgumentException("At least one item is required in the response");
        }

        return response;
    }
}

Step 4: Extract taxType and taxAmount Fields

Once the JSON is validated and parsed, we can easily extract the target fields by traversing the POJO structure.

public class FieldExtractor {
    public static void extractTaxFields(InvoiceResponse response) {
        for (Item item : response.getItems()) {
            if (item.getTaxes() != null) {
                for (Tax tax : item.getTaxes()) {
                    String taxType = tax.getTaxType();
                    Double taxAmount = tax.getTaxAmount();

                    // Process the extracted fields (e.g., print, store in database)
                    System.out.println("Extracted Tax Type: " + taxType);
                    if (taxAmount != null) {
                        System.out.println("Extracted Tax Amount: " + taxAmount);
                    } else {
                        System.out.println("Tax Amount is missing for this tax entry");
                    }
                }
            }
        }
    }

    // Example usage
    public static void main(String[] args) {
        String jsonResponse = "{ \"taxExempt\": false, \"billingAddress\": { \"addressLine1\": \"Millers Rd\", \"addressLine2\": \"\", \"city\": \"Bengaluru\", \"postalCode\": \"560052\", \"state\": \"KA\", \"country\": \"IN\", \"name\": null, \"email\": null }, \"shippingAddress\": null, \"billingAccountKey\": \"20000052\", \"invoiceKey\": null, \"date\": \"2018-01-01\", \"currency\": \"AUD\", \"taxNumber\": \"AACCL1660QSD002\", \"aggregateTax\": true, \"totalTax\": 0, \"items\": [ { \"taxes\": [ { \"taxType\": \"GST\" } ] } ] }";

        try {
            InvoiceResponse validatedResponse = JsonProcessor.validateAndParseJson(jsonResponse);
            extractTaxFields(validatedResponse);
        } catch (Exception e) {
            System.err.println("Validation/Extraction failed: " + e.getMessage());
        }
    }
}

Notes:

  • If you prefer not to use POJOs, you can use Jackson's Tree Model (JsonNode) to parse and traverse the JSON dynamically. This is useful if the JSON structure is unpredictable.
  • The example JSON you provided doesn't include a taxAmount field in the taxes array. The code handles this by using Double (nullable) and checking for nulls.
  • You can extend the validation logic to include more checks (e.g., valid currency code, non-negative totalTax, etc.) based on your requirements.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:08:13