我似乎无法使用 GSON 从 JSON 创建 POJO(计划旧 Java 对象)。我按照本教程学习了 T 但我仍然得到一个空对象。这是我的代码:
JSONHandler.java
public class JSONHandler
{
private Gson gson;
private InputStream is;
private Reader reader;
private TripList tripList;
public JSONHandler(InputStream is)
{
this.is = is;
gson = new Gson();
reader = new InputStreamReader(is);
tripList = gson.fromJson(reader, TripList.class);
}
public Gson getGson() {
return gson;
}
public void setGson(Gson gson) {
this.gson = gson;
}
TripList.java
public class TripList
{
@SerializedName("Line")
public String line;
@SerializedName("CurrentTime")
public int currentTime;
public List<Train> Trips;
}
火车.java
public class Train
{
@SerializedName("TripID")
public String tripID;
@SerializedName("Destination")
public String dest;
public List<Prediction> Predictions;
}
预测.java
public class Prediction
{
@SerializedName("StopID")
public int stopID;
@SerializedName("Stop")
public String stop;
@SerializedName("Seconds")
public int seconds;
}
蓝色.json
{
"TripList":
{
"CurrentTime":1342032950,
"Line":"Red",
"Trips": [
{
"TripID":"R982ECC1E",
"Destination":"Alewife",
"Predictions": [
{"StopID":"70094","Stop":"Ashmont","Seconds":370}
]
},
{
"TripID":"R982ECC78",
"Destination":"Ashmont",
"Note":"Big Red",
"Position":
{"Timestamp":1342032834,"Train":"1809","Lat":42.38725,"Long":-71.11894,"Heading":185},
"Predictions": [
{"StopID":"70067","Stop":"Harvard Square","Seconds":36},
{"StopID":"70069","Stop":"Central Square","Seconds":260}
]
}
]
}
}
JSON 格式将遵循此范例。当无法正确解析某些内容时,GSON 不会抛出错误,它只是返回一个令人讨厌的空值。格式或我处理 java 数据对象的方式有问题吗?任何帮助将非常感激