2013-07-20 137 views
0

我正在使用PHP生成從數據庫查詢中抓取的Json。結果是這樣的:Gson解碼php編碼Json

[ 
    { 
     "title":"Title 1", 
     "description":"This is description 1", 
     "add_date":"2013-07-17 10:07:53" 
    },{ 
     "title":"Title 2", 
     "description":"This is description 2", 
     "add_date":"2013-07-17 10:07:53" 
    } 
] 

我使用GSON分析數據,如下所示:

public class Search{ 

    public Search(String text){ 
     try{ 

      // Snipped (gets the data from the website) 

      Gson json = new Gson(); 
      Map<String, Event> events = json.fromJson(resultstring, new TypeToken<Map<String, Event>>(){}.getType()); 

      System.out.print(events.get("description")); 

     }catch(IOException ex){ 
      Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex); 
     } 

    } 
} 

class Event { 
    private String description; 
} 

這裏是試圖運行的代碼,我得到消息:

Exception in thread "AWT-EventQueue-0" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3

我將如何循環通過每一個獲得值descriptiontitle或兩者兼而有之?

回答

2

你在做什麼,你應該是好幾個更正去:

class Event { 
    private String description; 
    private String title; 
    @SerializedName("add_date") private String addDate; 

    public getDescription() { 
     return description; 
    } 
} 


public Search(String text){ 
    try{ 

     // Snipped (gets the data from the website) 

     Gson json = new Gson(); 
     Event[] events = json.fromJson(resultstring, Event[].class); 

     System.out.print(events[0].getDescription()); 

    }catch(IOException ex){ 
     Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex); 
    } 

} 

我糾正了bean類和改變你轉換到(的Event數組是什麼類型的,因爲這是你實際上是從PHP服務中獲得的);

+0

工程,但我得到這個錯誤:'找不到符號 符號:類SerialzedName 位置:類事件'。另外,你爲什麼要連線? –

+0

@RyanNaddy這是說明你不使用字段名和json屬性的直接對應關係。但是,您需要導入註釋。這就是你所得到的錯誤 –