2013-05-13 236 views
1

這是我以前的問題的延續。獲取JSON請求並將其轉換爲JSON後,我試圖將結果解析爲Java對象。使用GSON解析JSON

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 + 
     "]"; 
    } 
} 

回答

3

我假設你的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領域,所以我建議您將它們解析爲字符串,然後進行正確的轉換......否則您必須創建一個custom deserializer

+0

嗨啊,我剛打的錯誤,當我試圖解析..謝謝。 – jonleech 2013-05-14 01:05:47

1

上述代碼無法將值解釋爲類型FlightInfo,因爲Gson調用list.getClass()以獲取其類信息,但此方法返回一個原始類List.class。這意味着Gson無法知道這是類型爲列表< FlightInfo>的對象,而不僅僅是普通列表。

您可以通過爲您的泛型指定正確的參數化類型來解決此問題。您可以通過使用TypeToken類來完成此操作。

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

的更多信息,請gson-user-guide