2014-07-26 27 views
-2

我有一個PHP腳本返回JSON,如下圖所示:解析JSON在活動對象在android系統

[{"title":"Clothes are selling well","location":"Los Angeles","imageUrl":"xxx","pubDate":"2014-07-26 13:58:08","id":"1"},{"title":"Polo this summer","location":"UAE","imageUrl":"YYY","pubDate":"2014-07-26 18:05:26","id":"2"},{"title":"Samsung: New tablets","location":"Kuwait","imageUrl":"IIIIII","pubDate":"2014-07-26 18:05:26","id":"3"}] 

我需要在我的活動類來解析此JSON。有關如何做到這一點的任何建議?我將創建一個具有以下屬性的對象:

  1. 標題
  2. 位置
  3. 的ImageUrl
  4. pubdate的

在此先感謝

回答

2

在Android中解析JSON非常簡單。這是你如何解析當前的JSON - 如果你是新來解析JSON還有不少好教程對於這一點,像

//Assuming json holds your JSON as String 
    try { 
     //Create a JSON array 
     JSONArray jsonArray = new JSONArray(json); 

     //Iterate through all the JSON objects 
     for(int i=0;i<jsonArray.length();i++){ 

      //Get ith object 
      JSONObject item = jsonArray.getJSONObject(i); 

      //Get required data from the object 
      String title = (String) item.get("title"); 
      String location = (String) item.get("location"); 
      String imageUrl = (String) item.get("imageUrl"); 
      String pubDate = (String) item.get("pubDate"); 

      //You can now do anything with the data. 
      Log.i("TITLE", title); 
      Log.i("LOC", location); 
      Log.i("IMG_URL", imageUrl); 
      Log.i("P_DATE", pubDate);       

     }      

    } catch (JSONException e) { 
     Log.i("EXP", "Ooi..! There's an exception."); 
     e.printStackTrace(); 
    } 

-

0

創建按照這些屬性類。 下載谷歌 類實例名稱的GsonObjects 例子:

String json = "...."; 
Gson gson = new Gson(); 
Objects obj = (Objects) gson.fromJson(json,Objects.class); 

希望它幫助。

1

Jackson library可幫助您自動將數據綁定到JSON或從JSON綁定數據。

public class Object { 
    @JsonProperty 
    private String title; 
    @JsonProperty 
    private String location; 
    @JsonProperty 
    private String url; 

    @JsonPropery 
    private String pubDate; 
    @JsonProperty 
    private int id; 

    //Add set and get method. 
} 

爲了解析字符串,您需要使用ObjectMapper對象。

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally 
Object obj = mapper.readValue(/*your string*/, Object.class); 

否則,您可以輕鬆地使用Android JSONTokener手動執行操作。