简体   繁体   English

Null 值在 json 中返回,而在 java 中使用 gson

[英]Null values being returned in json while using gson in java

I have the following Json file which I am trying to read:我正在尝试阅读以下 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"
    }
  }
}

I used direct Object Mapping provided by Gson:我直接使用Gson提供的Object映射:

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

But it always resulted in:但它总是导致:

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

How can I get the data inside the other objects?如何获取其他对象中的数据?

Edit:编辑:

Here is the BillingInformation Class:这是账单信息 Class:

public class BillingInformation {
  @SerializedName("taxes")
  private Taxes taxes;

  @SerializedName("billTo")
  private BillTo billTo;

  @SerializedName("salesAgent")
  private SalesAgent salesAgent;

  @SerializedName("items")
  private Items items;
  }

and I have the usual getters and setters for the above fields.我有上述字段的常用 getter 和 setter。

You should create a class that looks like this:您应该创建一个如下所示的 class:

class Data {
  private BillingInformation billingInformation;
}

And then do the deserialization:然后进行反序列化:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM