Java中使用Gson解析JSON返回Null值的问题咨询
问题解决:Gson解析嵌套JSON字段全为null的处理方案
问题根源
你的JSON根结构是一个包含billingInformation键的顶层对象,但你直接用BillingInformation.class去解析整个JSON字符串。Gson无法在顶层JSON中找到与BillingInformation类字段匹配的键,因此所有属性都被初始化为null。
解决方案
提供两种可行的处理方式:
方式一:创建顶层包装类匹配JSON结构
新增一个顶层类来对应JSON的根节点,再通过该类获取嵌套的BillingInformation对象:
public class BillingRoot { @SerializedName("billingInformation") private BillingInformation billingInformation; // 标准Getter和Setter方法 }
修改解析代码:
String result = new String(Files.readAllBytes(Paths.get(path))); BillingRoot root = gson.fromJson(result, BillingRoot.class); BillingInformation billingInformation = root.getBillingInformation();
方式二:通过JsonObject手动提取嵌套节点
无需新增类,先将整个JSON解析为JsonObject,再提取目标节点进行转换:
String result = new String(Files.readAllBytes(Paths.get(path))); JsonObject rootJson = gson.fromJson(result, JsonObject.class); JsonElement billingInfoElement = rootJson.get("billingInformation"); BillingInformation billingInformation = gson.fromJson(billingInfoElement, BillingInformation.class);
额外检查项
确保你的嵌套类(Taxes、BillTo、SalesAgent、Items等)满足以下要求:
- 字段名与JSON中的键完全一致,或通过
@SerializedName标注匹配 - 数据类型匹配(比如JSON中
agentCode是数字,类中对应字段应为int;gst是浮点数,对应double类型) - 类中包含无参构造方法(Gson默认需要,若未显式定义,Java会自动生成)
内容的提问来源于stack exchange,提问作者user19204430
相关产品推荐
相关产品推荐

