我有以下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上获得了一个NPE异常信息= type.weight.days;
关于可能出现什么问题的任何建议?
答案 0 :(得分:0)
您的JSON格式不正确。仅查看days
元素,我们有:
"days": [
{
"weight": [
{
"bmi": 29.5,
"date": "2016-02-14",
"logId": 1455494399000,
"source": "API",
"time": "23:59:59",
"weight": 90.3
},
]
看着,你得到了:
,
列表weight
]
weight
}
0
上没有关闭days
(要完成,如果最终,
不存在,]
将关闭weight
,然后}
将关闭列表0
{1}},留下days
并且基础未公开。)
此外,您的第一个引号代替days
“
。我不确定GSON是否可以使用角度引号,但我知道JSON标准要求所有引号都为"
。
老实说,我很遗憾GSON没有因此而吐出错误。但是你获得NullPointerException的原因是因为"
被设置为默认值,因为GSON无法读取它的值。