我有一个这样的 Json 文件:
{
"airports": [
{
"fs": "VGO",
"iata": "VGO",
"icao": "LEVX",
"name": "Vigo Airport",
"city": "Vigo",
"cityCode": "VGO",
"stateCode": "SP",
"countryCode": "ES",
"countryName": "Spain and Canary Islands",
"regionName": "Europe",
"timeZoneRegionName": "Europe/Madrid",
"localTime": "2018-01-29T08:59:15.661",
"utcOffsetHours": 1,
"latitude": 42.224551,
"longitude": -8.634025,
"elevationFeet": 860,
"classification": 4,
"active": true,
"weatherUrl": "https://api.flightstats.com/flex/weather/rest/v1/json/all/VGO?codeType=fs",
"delayIndexUrl": "https://api.flightstats.com/flex/delayindex/rest/v1/json/airports/VGO?codeType=fs"
}
]
}
我想用它来创建一个机场对象。
public class Airport {
String iata;
String name;
String city;
String countryName;
String regionName;
String timeZoneRegionName;
double utcOffsetHours;
double latitude;
double longitude;
int elevationFeet;
@Override
public String toString() {
return "Airports{" +
"iata='" + iata + '\'' +
", name='" + name + '\'' +
", city='" + city + '\'' +
", countryName='" + countryName + '\'' +
", regionName='" + regionName + '\'' +
", timeZoneRegionName='" + timeZoneRegionName + '\'' +
", utcOffsetHours=" + utcOffsetHours +
", latitude=" + latitude +
", longitude=" + longitude +
", elevationFeet=" + elevationFeet +
'}';
}
}
我是这样读的:
public void imprimirJson(String fileName) {
String filePath = getCacheDir() + "/" + fileName + ".json";
Gson gson = new Gson();
Airport airport = null;
try {
airport = gson.fromJson(new FileReader(filePath), Airport.class);
} catch (FileNotFoundException e) {
}
Log.i("MSG", airport.toString());
}
但是如果我执行这段代码,日志会打印一个空数组
public void printJson(String fileName) {
String filePath = getCacheDir() + "/" + fileName + ".json";
Gson gson = new Gson();
Airport airport = null;
try {
airport = gson.fromJson(new FileReader(filePath), Airport.class);
} catch (FileNotFoundException e) {
}
Log.i("MSG", airport.toString());
}
我认为问题在于第一个属性具有我想要的信息数组。但我不知道如何访问这些信息。你能给我指路吗?
最佳答案
创建一个类 MyAirports.java。
public class MyAirports{
List<Airport> airports;
public List<Airport> getAirportList()
{
return this.airports;
}
}
然后做,
public void printJson(String fileName) {
String filePath = getCacheDir() + "/" + fileName + ".json";
Gson gson = new Gson();
MyAirports airports = null;
try {
//airport = gson.fromJson(new FileReader(filePath), Airport.class);
airports = gson.fromJson(new FileReader(filePath), MyAirports.class);
} catch (FileNotFoundException e) {
}
Log.i("MSG", airports.getAirportList().get(0).toString());
}
关于java - 我无法使用 Gson 将 Json 文件解析为 java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48498879/