简体   繁体   English

使用GSON解析JSON

[英]Parsing JSON using GSON

This is a continuation of my previous question. 这是我先前问题的延续。 After getting the JSON request and turning it into a JSON, I am trying to parse the result into Java Object. 获得JSON请求并将其转换为JSON之后,我尝试将结果解析为Java Object。

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;
  }
}

I tried: 我试过了:

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

but it got me null, I am sure I need to parse it into a List since my data has a lot of entries. 但是它使我为空,我确信我需要将其解析为一个列表,因为我的数据有很多条目。

sample of the JSON 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": []
  }
]

and my FlightInfo.class 和我的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 +
      "]";
  }
}

I assume that your JSON response is surrounded by { } , otherwise it's not valid JSON... 我假设您的JSON响应被{ }包围,否则它不是有效的JSON ...

That said, you need another class to parse your JSON response, for example: 也就是说,您需要另一个类来解析JSON响应,例如:

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

Now you can parse your response with: 现在,您可以使用以下方式解析您的回复:

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

Note : looking at your class FlightInfo and your JSON response, I think you'll have trouble parsing your Date and Time fields, so I suggest you to parse them as strings and then do the correct transformation... or you'll have to create a custom deserializer . 注意 :查看类FlightInfo和JSON响应,我认为您在解析DateTime字段时会遇到麻烦,因此建议您将它们解析为字符串,然后进行正确的转换...否则您将不得不创建一个自定义解串器

The above code fails to interpret value as type FlightInfo because Gson invokes list.getClass() to get its class information, but this method returns a raw class, List.class. 上面的代码无法将值解释为FlightInfo类型,因为Gson调用list.getClass()来获取其类信息,但是此方法返回了一个原始类List.class。 This means that Gson has no way of knowing that this is an object of type List < FlightInfo>, and not just plain List. 这意味着Gson无法知道这是List <FlightInfo>类型的对象,而不仅仅是普通List。

You can solve this problem by specifying the correct parameterized type for your generic type. 您可以通过为泛型类型指定正确的参数化类型来解决此问题。 You can do this by using the TypeToken class. 您可以通过使用TypeToken类来实现。

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

for more information check gson-user-guide 有关更多信息,请查看gson-user-guide

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM