You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Gson解析JSON文件到Java Airport对象失败求助

解决Gson解析JSON为空对象的问题

你猜的完全没错!问题核心就是JSON的顶层结构——你的JSON最外层是一个包含airports数组的对象,但你直接尝试把整个JSON解析成单个Airport对象,Gson找不到对应的匹配字段,自然就返回空对象了。另外还有个容易忽略的细节:你的Airport类字段是默认包访问权限,如果解析代码和Airport不在同一个包下,Gson可能无法直接给这些字段赋值,这也会导致属性为空。

下面给你两种可行的解决方法:

方法一:创建顶层包装类(推荐)

这是最直观且符合代码规范的方式,我们创建一个和JSON顶层结构完全匹配的类,用来包裹airports数组:

1. 修复Airport类的字段访问权限

先把字段改成public,或者添加getter/setter方法,确保Gson能顺利访问并赋值:

public class Airport {
    public String iata;
    public String name;
    public String city;
    public String countryName;
    public String regionName;
    public String timeZoneRegionName;
    public double utcOffsetHours;
    public double latitude;
    public double longitude;
    public 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 +
                '}';
    }
}

2. 创建顶层包装类

public class AirportResponse {
    public List<Airport> airports;
}

3. 修改解析代码

现在可以先解析成AirportResponse对象,再取出数组里的目标Airport实例:

public void imprimirJson(String fileName) {
    String filePath = getCacheDir() + "/" + fileName + ".json";
    Gson gson = new Gson();
    try {
        AirportResponse response = gson.fromJson(new FileReader(filePath), AirportResponse.class);
        // 你的JSON里airports数组只有一个元素,直接取第一个即可
        if (response != null && response.airports != null && !response.airports.isEmpty()) {
            Airport airport = response.airports.get(0);
            Log.i("MSG", airport.toString());
        } else {
            Log.i("MSG", "未找到有效机场数据");
        }
    } catch (FileNotFoundException e) {
        // 不要留空catch块,打印异常能帮你快速定位问题
        e.printStackTrace();
        Log.e("MSG", "JSON文件不存在", e);
    }
}

方法二:直接解析数组(无需额外类)

如果不想创建包装类,可以先把JSON解析成JsonObject,再提取airports数组,最后解析成List<Airport>:

public void imprimirJson(String fileName) {
    String filePath = getCacheDir() + "/" + fileName + ".json";
    Gson gson = new Gson();
    try {
        JsonObject jsonObject = gson.fromJson(new FileReader(filePath), JsonObject.class);
        JsonArray airportsArray = jsonObject.getAsJsonArray("airports");
        // 使用TypeToken获取List<Airport>的泛型类型
        Type listType = new TypeToken<List<Airport>>() {}.getType();
        List<Airport> airports = gson.fromJson(airportsArray, listType);
        
        if (!airports.isEmpty()) {
            Airport airport = airports.get(0);
            Log.i("MSG", airport.toString());
        } else {
            Log.i("MSG", "未找到有效机场数据");
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.e("MSG", "JSON文件不存在", e);
    }
}

两种方法都能解决你的问题,推荐第一种,因为代码结构更清晰,也符合面向对象的设计思路。另外记得永远不要留空的catch块,异常信息是调试的重要线索。

内容的提问来源于stack exchange,提问作者TapateBen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:57:32