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

Android铁路查询应用:嵌套JSON解析与实体类创建技术求助

解决Railway API JSON数据解析与实体类创建问题

嘿,我懂你在开发Android铁路信息应用时,碰到了Railway API返回的JSON解析和实体类创建的难题——这确实是对接第三方API时很多开发者都会踩的坑。咱们一步步来解决:

首先先补全你提供的截断JSON(假设完整结构,方便后续处理):

{
  "debit": 1,
  "total": 3,
  "response_code": 200,
  "trains": [
    {
      "days": [
        { "code": "MON", "runs": "Y" },
        { "code": "TUE", "runs": "Y" },
        { "code": "WED", "runs": "N" },
        { "code": "THU", "runs": "Y" },
        { "code": "FRI", "runs": "Y" },
        { "code": "SAT", "runs": "N" },
        { "code": "SUN", "runs": "Y" }
      ],
      "train_number": "12345",
      "train_name": "Sample Express",
      "from_station": {
        "code": "DEL",
        "name": "New Delhi"
      },
      "to_station": {
        "code": "MUM",
        "name": "Mumbai Central"
      },
      "departure_time": "10:00",
      "arrival_time": "20:30",
      "duration": "10h 30m"
    }
  ]
}

1. 自动生成实体类(告别手动编写的繁琐)

Android开发里最省心的方式是用工具自动生成实体类,完全不用自己逐字段手写:

  • 如果你用Kotlin,Android Studio自带一键生成功能:把完整JSON复制后,打开File > New > Paste Special > Paste JSON as Kotlin Class,就能直接生成对应的数据类。
  • 如果你用Java,可以用Android Studio的GsonFormat插件,或者复制JSON到工具里一键生成带注解的实体类。

Kotlin数据类示例

data class RailwayResponse(
    val debit: Int,
    val total: Int,
    val response_code: Int,
    val trains: List<Train>
)

data class Train(
    val days: List<Day>,
    val train_number: String,
    val train_name: String,
    val from_station: Station,
    val to_station: Station,
    val departure_time: String,
    val arrival_time: String,
    val duration: String
)

data class Day(
    val code: String,
    val runs: String
)

data class Station(
    val code: String,
    val name: String
)

Java实体类示例(带Gson注解)

import com.google.gson.annotations.SerializedName;
import java.util.List;

public class RailwayResponse {
    @SerializedName("debit")
    private int debit;
    @SerializedName("total")
    private int total;
    @SerializedName("response_code")
    private int responseCode;
    @SerializedName("trains")
    private List<Train> trains;

    // Getters & Setters
    public int getDebit() { return debit; }
    public void setDebit(int debit) { this.debit = debit; }
    public int getTotal() { return total; }
    public void setTotal(int total) { this.total = total; }
    public int getResponseCode() { return responseCode; }
    public void setResponseCode(int responseCode) { this.responseCode = responseCode; }
    public List<Train> getTrains() { return trains; }
    public void setTrains(List<Train> trains) { this.trains = trains; }
}

public class Train {
    @SerializedName("days")
    private List<Day> days;
    @SerializedName("train_number")
    private String trainNumber;
    @SerializedName("train_name")
    private String trainName;
    @SerializedName("from_station")
    private Station fromStation;
    @SerializedName("to_station")
    private Station toStation;
    @SerializedName("departure_time")
    private String departureTime;
    @SerializedName("arrival_time")
    private String arrivalTime;
    @SerializedName("duration")
    private String duration;

    // Getters & Setters省略,按需生成
}

public class Day {
    @SerializedName("code")
    private String code;
    @SerializedName("runs")
    private String runs;

    // Getters & Setters
    public String getCode() { return code; }
    public void setCode(String code) { this.code = code; }
    public String getRuns() { return runs; }
    public void setRuns(String runs) { this.runs = runs; }
}

public class Station {
    @SerializedName("code")
    private String code;
    @SerializedName("name")
    private String name;

    // Getters & Setters
    public String getCode() { return code; }
    public void setCode(String code) { this.code = code; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

2. 用Gson解析JSON数据

假设你已经通过OkHttp/Retrofit拿到了API返回的JSON字符串,用Gson解析非常简单:

Kotlin示例

import com.google.gson.Gson

// 假设jsonString是API返回的完整JSON内容
val gson = Gson()
val railwayResponse = gson.fromJson(jsonString, RailwayResponse::class.java)

// 遍历列车数据展示
railwayResponse.trains.forEach { train ->
    println("列车编号:${train.train_number},名称:${train.train_name}")
    // 处理运行天数
    train.days.forEach { day ->
        println("${day.code} 是否运行:${if (day.runs == "Y") "是" else "否"}")
    }
}

Java示例

import com.google.gson.Gson;

// 假设jsonString是API返回的完整JSON内容
Gson gson = new Gson();
RailwayResponse railwayResponse = gson.fromJson(jsonString, RailwayResponse.class);

// 遍历列车数据展示
for (Train train : railwayResponse.getTrains()) {
    System.out.println("列车编号:" + train.getTrainNumber() + ",名称:" + train.getTrainName());
    // 处理运行天数
    for (Day day : train.getDays()) {
        System.out.println(day.getCode() + " 是否运行:" + (day.getRuns().equals("Y") ? "是" : "否"));
    }
}

3. 关键注意事项

  • 确保你拿到的是完整且格式合法的JSON,你提供的原JSON是截断状态,这会直接导致解析失败,一定要先获取到完整的API响应。
  • 如果API返回的字段可能为null,Kotlin里用可空类型(比如String?),Java里用包装类(比如Integer代替int)避免空指针。
  • 要是你用Retrofit,可以直接把实体类作为Call的泛型参数,Retrofit会自动完成解析,不用手动调用Gson:
    interface RailwayApiService {
        @GET("your-api-endpoint")
        suspend fun getTrainInfo(): Response<RailwayResponse>
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:44:41