1

这是我上一个问题的延续。在获得 JSON 请求并将其转换为 JSON 后,我试图将结果解析为 Java 对象。

public class NetClientGet {

  @SuppressWarnings("unchecked")
  public static void main(String[] args) {
    String urlYesterday = "http://fids.changiairport.com/webfids/fidsp/get_flightinfo_cache.php?d=-1&type=pa&lang=en";
    String yesterdayJSON = getDataFromWeb(urlYesterday);
    //System.out.println("yesterdayJSON : " + yesterdayJSON);
    //jsonArray.add(yesterdayJSON);
    Gson gson = new Gson();
    List<FlightInfo> flightArray = (List<FlightInfo>) gson.fromJson(yesterdayJSON, FlightInfo.class);
    System.out.println("flightArray : " + flightArray);
  }

  private static String getDataFromWeb(String targetURL) {
    try {
      URL url = new URL(targetURL);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      if (conn.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
      }
      BufferedReader br;
      if ("gzip".equalsIgnoreCase(conn.getContentEncoding())) {
        br = new BufferedReader(new InputStreamReader(
        (new GZIPInputStream(conn.getInputStream()))));
      } else {
        br = new BufferedReader(new InputStreamReader(
        (conn.getInputStream())));
      }
      // Retrieve data from server
      String output = null;
      final StringBuffer buffer = new StringBuffer(16384);
      while ((output = br.readLine()) != null) {
        buffer.append(output);
      }
      conn.disconnect();
      // Extract JSON from the JSONP envelope
      String jsonp = buffer.toString();
      String json = jsonp.substring(jsonp.indexOf("(") + 1, //this is the index of the callback envelope
      jsonp.lastIndexOf(")"));
      //System.out.println("Output from server");
      //System.out.println(json);
      return json;
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
}

我试过了:

Gson gson = new Gson();
FlightInfo flightArray = gson.fromJson(yesterdayJSON, FlightInfo.class);

但它让我为空,我确信我需要将它解析成一个列表,因为我的数据有很多条目。

JSON 样本

"flights": [
  {
    "date": "2013-05-12",
    "scheduled_time": "23:30",
    "estimated_time": "23:09*",
    "airline": "TR",
    "flight_no": "TR2109",
    "airport": "BKK",
    "origin": "Bangkok (Suvarnabhumi)",
    "via": "",
    "terminal": "2",
    "belt": "35",
    "status": "Landed",
    "airline_name": "TIGER AIRWAYS",
    "airline_alias": "",
    "unixtime": "1368372600",
    "master_flight_no": "TR2109",
    "slave_flight_no": []
  }
]

和我的 FlightInfo.class

import java.sql.Time;
import java.util.Date;

public class FlightInfo {
  private Date date;
  private Time scheduled_time;
  private Time estimated_time;
  private String airline;
  private String flight_no;
  private String airport;
  private String origin;
  private String via;
  private String terminal;
  private String belt;
  private String status;
  private String airline_name;

  public Date getDate() {
    return date;
  }
  public void setDate(Date date) {
    this.date = date;
  }
  public Time getScheduled_time() {
    return scheduled_time;
  }
  public void setScheduled_time(Time scheduled_time) {
    this.scheduled_time = scheduled_time;
  }
  public Time getEstimated_time() {
    return estimated_time;
  }
  public void setEstimated_time(Time estimated_time) {
    this.estimated_time = estimated_time;
  }
  public String getAirline() {
    return airline;
  }
  public void setAirline(String airline) {
    this.airline = airline;
  }
  public String getFlight_no() {
    return flight_no;
  }
  public void setFlight_no(String flight_no) {
    this.flight_no = flight_no;
  }
  public String getAirport() {
    return airport;
  }
  public void setAirport(String airport) {
    this.airport = airport;
  }
  public String getOrigin() {
    return origin;
  }
  public void setOrigin(String origin) {
    this.origin = origin;
  }
  public String getVia() {
    return via;
  }
  public void setVia(String via) {
    this.via = via;
  }
  public String getTerminal() {
    return terminal;
  }
  public void setTerminal(String terminal) {
    this.terminal = terminal;
  }
  public String getBelt() {
    return belt;
  }
  public void setBelt(String belt) {
    this.belt = belt;
  }
  public String getStatus() {
    return status;
  }
  public void setStatus(String status) {
    this.status = status;
  }
  public String getAirline_name() {
    return airline_name;
  }
  public void setAirline_name(String airline_name) {
    this.airline_name = airline_name;
  }
  @Override
  public String toString() {
    return "FlightInfo [date=" + date + ", scheduled_time=" + scheduled_time +
      ", estimated_time=" + estimated_time +
      ", airline=" + airline +
      ", flight_no=" + flight_no +
      ", airport=" + airport +
      ", origin=" + origin +
      ", via=" + via +
      ", terminal=" + terminal +
      ", belt=" + belt +
      ", status=" + status +
      ", airline_name=" + airline_name +
      "]";
  }
}
4

2 回答 2

4

我假设您的 JSON 响应被包围{ },否则它不是有效的 JSON...

也就是说,您需要另一个类来解析您的 JSON 响应,例如:

public class Response {    
    private List<FlightInfo> flights;        
    //getters & setters
}

现在您可以使用以下方法解析您的响应:

Gson gson = new Gson();
Response response = gson.fromJson(yesterdayJSON, Response .class);
List<FlightInfo> flightArray = response.getFlights();

注意:查看您的课程FlightInfo和 JSON 响应,我认为您在解析DateTime字段时会遇到问题,所以我建议您将它们解析为字符串,然后进行正确的转换......或者您必须创建一个自定义解串器

于 2013-05-13T11:24:21.540 回答
1

上面的代码无法将 value 解释为 FlightInfo 类型,因为 Gson 调用 list.getClass() 来获取其类信息,但此方法返回一个原始类 List.class。这意味着 Gson 无法知道这是一个 List < FlightInfo> 类型的对象,而不仅仅是普通的 List。

您可以通过为泛型类型指定正确的参数化类型来解决此问题。您可以使用 TypeToken 类来做到这一点。

Type listType = new TypeToken<List<Bar>>() {}.getType();
gson.toJson(list, listType );
gson.fromJson(json, listType );

有关更多信息,请查看gson-user-guide

于 2013-05-13T19:38:07.960 回答