
本文详解如何用 gson 库精准解析具有深层嵌套结构(如 `billinginformation → taxes`、`items → item[]`)的 json 文件,避免手动逐层取值错误,并实现类型安全的对象映射与列表反序列化。
在 Java 中使用 Gson 解析 JSON 时,若 JSON 结构存在多层嵌套(例如外层为 {"billingInformation": {...}},内部再包含 taxes、billTo、items 等子对象),直接调用 getAsJsonObject() 逐级访问虽可行,但易出错、可维护性差,且无法充分利用 Gson 的自动反序列化能力。更专业、健壮的做法是:定义匹配的 Java 类结构 + 使用 Gson.fromJson() 直接映射整棵树。
✅ 推荐方案:面向对象建模 + 全量反序列化
首先,根据 JSON 结构定义完整 POJO 层级(注意字段命名与 JSON key 一致,或使用 @SerializedName 注解):
public class BillingResponse {
private BillingInformation billingInformation;
// getter/setter
}
public class BillingInformation {
private Taxes taxes;
private BillTo billTo;
private SalesAgent salesAgent;
private Items items;
// getters/setters
}
public class Taxes {
@SerializedName("gst") private double gst;
@SerializedName("hst") private double hst;
// getters/setters
}
public class BillTo {
private String name;
private String address;
private String phoneNumber; // 注意:JSON 中 phoneNumber 是字符串,非数字!
// getters/setters
}
public class SalesAgent {
private String name;
private int agentCode;
// getters/setters
}
public class Items {
private List- item;
private String currency;
// getters/setters
}
public class Item {
private String hsnCode;
private String description;
private String originCountry;
private int quantity; // JSON 中为数字,建议用 int/long
private double unitPrice; // JSON 中为浮点数
// getters/setters
}
⚠️ 关键注意事项:phoneNumber 在原始 JSON 中是带空格的字符串 "601 855 1249",绝不可声明为 int 或 long,否则 Gson 解析会抛 JsonParseException;所有嵌套对象字段名需与 JSON key 完全匹配(大小写敏感),或统一用 @SerializedName("xxx") 显式声明;数组字段(如 "item": [...])必须声明为 List,Gson 才能正确识别并反序列化。
? 一行代码完成全量解析
Gson gson = new Gson();
BillingResponse response = gson.fromJson(
Files.newBufferedReader(Paths.get(bill)),
BillingResponse.class
);
// 后续可安全访问任意层级
double gst = response.getBillingInformation().getTaxes().getGst();
String buyerName = response.getBillingInformation().getBillTo().getName();
Item firstItem = response.getBillingInformation().getItems().getItem().get(0);
System.out.println("First item: " + firstItem.getDescription());? 若需动态遍历(不依赖固定类),仍推荐 TypeToken 方式
当部分结构动态或尚未建模时,可结合 JsonElement 与 TypeToken 安全提取:
Reader reader = Files.newBufferedReader(Paths.get(bill));
JsonObject root = JsonParser.parseReader(reader).getAsJsonObject();
JsonObject billing = root.getAsJsonObject("billingInformation");
// 提取 items.item 数组(推荐)
JsonElement itemsArray = billing.getAsJsonObject("items").get("item");
Type itemTypeList = new TypeToken>(){}.getType();
List- itemList = new Gson().fromJson(itemsArray, itemTypeList);
for (Item item : itemList) {
System.out.printf("HSN: %s, Desc: %s, Price: $%.2f%n",
item.getHsnCode(), item.getDescription(), item.getUnitPrice());
}
✅ 总结:最佳实践清单
- ✅ 优先建模 POJO:结构清晰、类型安全、IDE 支持强、易于单元测试;
- ✅ 校验 JSON 合法性:使用 jsonlint.com 确保无语法错误(如引号缺失、逗号遗漏);
- ✅ 字符串字段勿强转数字:"601 855 1249" 必须映射为 String;
- ✅ 数组用 List
+ TypeToken :避免 getAsJsonArray() 后手动循环解析; - ❌ 避免深度 getAsJsonObject(...).getAsJsonObject(...).get(...) 链式调用——易 NullPointerException 且难以调试。
通过结构化建模与 Gson 的强类型反序列化,你不仅能准确读取多层嵌套 JSON,还能为后续业务逻辑(如计算税费、生成发票 PDF、存入数据库)提供稳定、可扩展的数据基础。










