【问题标题】:GSON from JSON nested object null pointer exception来自 JSON 嵌套对象空指针异常的 GSON
【发布时间】:2016-03-04 12:19:04
【问题描述】:

我有以下 JSON 文件:

{
   “weight": {
      "type": "weight",
      "range": [
         "2016-02-15",
         "2016-02-16",
         "2016-02-17",
         "2016-02-18",
         "2016-02-19",
         "2016-02-20",
         "2016-02-21"
      ],
      "days": [
         {
            "weight": [
               {
                  "bmi": 29.5,
                  "date": "2016-02-14",
                  "logId": 1455494399000,
                  "source": "API",
                  "time": "23:59:59",
                  "weight": 90.3
               },
      ]
}

然后,我希望将此 JSON 添加到以下类。

public class fitbitTypeWeight {
    public fitbitDays weight;
}

public class fitbitDays {
    public fitbitDayWeight days;
}

public class fitbitDayWeight {
    public fitbitWeight weight;
}

public class fitbitDayWeight {
    public fitbitWeight weight;
}

然后,我有下面的代码来尝试解析它。

public static void readJSON() {
    Gson gson = new Gson();  
    type = gson.fromJson(file, fitbitTypeWeight.class);
    GsonBuilder builder = new GsonBuilder();
    gson = builder.create();
    createFitBitInfo();
}

private static void createFitBitInfo() throws ITrustException{
    RemoteMonitoringDAO db = new RemoteMonitoringDAO(prodDAO);
    RemoteMonitoringDataBean temp=new RemoteMonitoringDataBean();
    fitbitDayWeight info = type.weight.days;
    temp.setFitbitWeight(info.weight.weight);
    temp.setFitbitDate(info.weight.date);
    temp.setLoggedInMID(userID);
    db.storeFitbitData(temp);
}

但是,我在 fitbitDayWeight info = type.weight.days; 上遇到 NPE 异常;

对可能出现的问题有什么建议吗?

【问题讨论】:

    标签: java json nullpointerexception gson


    【解决方案1】:

    您的 JSON 格式不正确。只看days 元素,我们有:

    "days": [
      {
        "weight": [
          {
            "bmi": 29.5,
            "date": "2016-02-14",
            "logId": 1455494399000,
            "source": "API",
            "time": "23:59:59",
            "weight": 90.3
          },
    ]
    

    看看,你有:

    • 悬空,列表weight
    • 没有关闭列表] weight
    • 在列表days0 上没有关闭}

    (完整地说,如果最终的, 不存在,] 将关闭weight 然后} 将关闭列表0 中的对象days,留下days 和基础未关闭.)

    此外,您的第一个报价是,而不是"。我不确定 GSON 是否可以使用角度引号,但我知道 JSON 标准要求在所有引号中使用 "

    老实说,我有点惊讶 GSON 不会因此而在加载时吐出错误。但是你得到 NullPointerException 的原因是因为 type.weight.days 被设置为默认值,因为 GSON 无法读取它的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      相关资源
      最近更新 更多