在java中使用gson时,在json中返回空值

35g0bw71  于 2023-01-27  发布在  Java
关注(0)|答案(1)|浏览(164)

我有下面的Json文件,我正在尝试读取:

{
  "billingInformation": {
    "taxes": {
      "gst": 2.5,
      "hst": 7.8
    },
    "billTo": {
      "name" : "Mike",
      "address" : "123, Lake Shore Drive, California",
      "phoneNumber" : "601 855 1249"
    },
    "salesAgent": {
      "name" : "Charlotte Thompson",
      "agentCode" : 44551
    },
    "items": {
      "item": [
        {
          "hsnCode": "5112",
          "description": "TV Set",
          "originCountry": "US",
          "quantity": 1,
          "unitPrice": 150.00
        }
      ],
      "currency": "USD"
    }
  }
}

我使用了Gson提供的直接对象Map:

result = new String(Files.readAllBytes(Paths.get(path)));
BillingInformation billingInformation = gson.fromJson(result, BillingInformation.class);

但结果总是:

class BillingInformation {
    taxes: null
    billTo: null
    salesAgent: null
    items: null
}

我怎样才能得到其他对象内部的数据?

kwvwclae

kwvwclae1#

您应该创建一个如下所示的类:

class Data {
  private BillingInformation billingInformation;
}

然后执行反序列化:

Data fromFile = gson.fromJson(result, Data.class);

相关问题