2014-03-27 2 views
1

나는 하루의 더 나은 부분을 위해 GSON과 싸워왔다. 글쎄, 안드로이드에 대한 목록의 나의 일반적인 비 이해만큼 나는 GSON만큼 생각하지 않는다. 기본적으로 무엇을 내가 각이 목록의 포맷 및 표시됩니다 JSON 2 개 배열, 수신하고있다 일어나고있다 : 나는 잘 개별 문자열을 읽을 수있어안드로이드 JSON 파싱 배열에 GSON

Adventures: 
+-------------+ 
| Adventure 1 | 
+-------------+ 
| Adventure 2 | 
+-------------+ 
Events: 
+-------------+ 
| Event 1 | 
+-------------+ 
| Event 2 | 
+-------------+ 

을, 그러나 나는받지 못했습니다 이것을 배열로 옮기는 내 머리. 내가 잡있어 JSON 형식은 다음과 같습니다

{ 
"events": [ 
    { 
     "eid": "11111111", 
     "bid": "aaaaaaaa", 
     "bname": "Example Business 1", 
     "start": "3/26/14 @ 6pm", 
     "end": "3/27/14 @ 2am", 
     "points": "50", 
     "title": "Example Event 1", 
     "description": "Example Event Description", 
     "cat": "Nightlife", 
     "type": "Bar", 
     "subtype": "Karaoke", 
     "valid": true 
    }, 
    { 
     "eid": "22222222", 
     "bid": "bbbbbbbb", 
     "bname": "Example Business 2", 
     "start": "3/26/14 @ 6pm", 
     "end": "3/27/14 @ 2am", 
     "points": "50", 
     "title": "Example Event 2", 
     "description": "Example Event Description", 
     "cat": "Nightlife", 
     "type": "Comedy", 
     "subtype": "General", 
     "valid": true 
    }, 
    { 
     "eid": "33333333", 
     "bid": "cccccccc", 
     "bname": "Example Business 3", 
     "start": "3/26/14 @ 6pm", 
     "end": "3/27/14 @ 2am", 
     "points": "150", 
     "title": "Example Event 3", 
     "description": "Example Event Description", 
     "cat": "Dining", 
     "type": "Restraunt", 
     "subtype": "Chinese", 
     "valid": true 
    } 
], 
"adventures": [ 
    { 
     "aid": "11111111", 
     "bid": "aaaaaaaa", 
     "start": "3/26/14 6pm", 
     "end": "3/27/14 2am", 
     "points": "150", 
     "title": "Example Adventure 1", 
     "description": "Example Adventure Description", 
     "cat": "Nightlife", 
     "type": "Bar", 
     "subtype": "Karaoke", 
     "steps_comp": "2", 
     "total_steps": "5", 
     "valid": true 
    }, 
    { 
     "aid": "22222222", 
     "bid": "bbbbbbbb", 
     "start": "3/26/14 6pm", 
     "end": "3/27/14 2am", 
     "points": "250", 
     "title": "Example Adventure 2", 
     "description": "Example Adventure Description", 
     "cat": "Nightlife", 
     "type": "Bar", 
     "subtype": "Neighborhood", 
     "steps_comp": "0", 
     "total_steps": "5", 
     "valid": true 
    } 
] 

} 나는 다음과 JSON을 구문 분석하고있어

(발리 코드 포함) :

RequestQueue queue = Volley.newRequestQueue(this); 
    JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, full_url, null, new Response.Listener<JSONObject>() { 
     @Override 
     public void onResponse(JSONObject response) { 
      String example = response.toString(); 
      Log.e("JSON Response", example); 

      try { 
       JsonParser jsonParser = new JsonParser(); 
       JsonObject jo = (JsonObject)jsonParser.parse(example); 
       JsonArray jsonArr = jo.getAsJsonArray("events"); 
       //jsonArr. 
       Gson googleJson = new Gson(); 
       ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class); 

       System.out.println("List size is : "+jsonObjList.size()); 
       System.out.println("List Elements are : "+jsonObjList.toString()); 

       for (int i = 0; i < jsonObjList.size(); i++){ 
         String item = jsonObjList.get(i).toString(); 
         System.out.println("Item " + i + " : " + item); 
       } 

       Toast.makeText(getApplicationContext(), "0: "+jsonObjList.get(0), 
         Toast.LENGTH_LONG).show(); 
      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      Toast.makeText(getApplicationContext(), "blah", 
       Toast.LENGTH_LONG).show(); 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      // TODO Auto-generated method stub 
     } 
    } 
); 
queue.add(jsObjRequest); 

내가 각 행을 단지 받고 있어요 괜찮아요.하지만 그것은 단지 하나의 문자열 일 뿐이므로 각 요소에 대한 개별 요소를 얻을 수는 없습니다. 나는 for 루프 안에서 또 다른 GSON 호출을해야 할 필요가 있다고 생각하고있다. 이것은 지저분 해 보인다. 나는 약간의 googleing을 해왔다. (나는 이걸 어떻게 얻었 는가?)하지만이 작품들을 만들기 위해 조각들을 모아 놓을 수는 없다. 어떤 도움을 주시면 감사하겠습니다.

답변

5

먼저 클래스를 생성 예를 들어 :

public class Event { 

    private String bid; 
    private int eid; 

} 

public class Adventure { 
    private String bid; 
    private int eid; 
// rest of the fields 
} 

그리고, 이러한 개체가 포함 된 클래스 생성 : 다음과 같이 코드에서

public class JsonResponse { 
    private ArrayList<Event> events; 
    private ArrayList<Adventure> adventures; 
} 

을, 당신은 역 직렬화 할 수 있어야한다 각 JsonAarry가 값을 보유 할 때마다

public class Events { 
    private String eid; 
    private String bid; 
    private String bname; 
    private String start; 
    private String end; 
    private String points; 
    private String title; 
    private String description; 
    private String cat; 
    private String type; 
    private String subtype; 
    private boolean valid; 
    @Override 
    public String toString() { 
     return "Events [eid=" + eid + ", bid=" + bid + ", bname=" + bname 
       + ", start=" + start + ", end=" + end + ", points=" + points 
       + ", title=" + title + ", description=" + description 
       + ", cat=" + cat + ", type=" + type + ", subtype=" + subtype 
       + ", valid=" + valid + "]"; 
    } 

} 

public class Adventures { 
    private String aid; 
    private String bid; 
    private String start; 
    private String end; 
    private String points; 
    private String title; 
    private String description; 
    private String cat; 
    private String type; 
    private String subtype; 
    private String steps_comp; 
    @Override 
    public String toString() { 
     return "Adventures [aid=" + aid + ", bid=" + bid + ", start=" + start 
       + ", end=" + end + ", points=" + points + ", title=" + title 
       + ", description=" + description + ", cat=" + cat + ", type=" 
       + type + ", subtype=" + subtype + ", steps_comp=" + steps_comp 
       + ", total_steps=" + total_steps + ", valid=" + valid + "]"; 
    } 
    private String total_steps; 
    private boolean valid; 

} 

지금 전체 응답을

public class ResponseHolder { 
    private ArrayList<Events> events; 
    private ArrayList<Adventures> adventures; 
    @Override 
    public String toString() { 
     return "ResponseHolder [events=" + events + ", adventures=" 
       + adventures + "]"; 
    } 
    public ArrayList<Events> getEvents() { 
     return events; 
    } 
    public ArrayList<Adventures> getAdventures() { 
     return adventures; 
    } 
} 

마지막

Gson googleJson = new Gson(); 
ResponseHolder rh= googleJson.fromJson(jsonArr, ResponseHolder.class); 

를 개최하는 클래스를 생성하고

 for(Events e: rh.getEvents()){ 
      System.out.println(e.toString()); 
     } 

     for(Adventures e: rh.getAdventures()){ 
      System.out.println(e.toString()); 
     } 
+1

그 일은 챔피언을 좋아했습니다. 고맙습니다. –

+0

@NativeNerd, 기꺼이 도와 드리겠습니다. –

0

나는 당신을 얻을 질수하지만 난 당신의 JSON 객체 각각에 대해 루프

에 대한
jsonobject = jsonArr.getJSONObject(i); 
    if (jsonobject != null) 
    { 
    String ID= jsonobject.getString("eid"); 
    String BID= jsonobject.getString("bid"); 

// Like this implement for other jsonobjects 

    } 
1

만들기 자바 객체에 그래서 당신이 코드 경우는 jsonarray에서 각 값을 얻는 방법에 어려움을 겪고있다 생각합니다.

Gson googleJson = new Gson(); 
JsonResponse jsonObjList = googleJson.fromJson(jsonArr, JsonResponse .class); 
0
 I have same problem. and i have json like this. 

      { 
       "latest_posting": [ 
        { 
         "posting_id": "7", 
         "posting_title": "Ring", 
         "photo_img": "images/posting/IMG_12121212.png.png", 
         "normal_price": null 
        }, 
        { 
         "posting_id": "8", 
         "posting_title": "dsadsd", 
         "photo_img": "images/posting/IMG_1212121216.jpg", 
         "normal_price": null 
        }, 
        { 
         "posting_id": "9", 
         "posting_title": "dasd", 
         "photo_img": "images/posting/IMG_121212122.png", 
         "normal_price": null 
        } 
       ], 
       "promotion_litsing": [ 
        { 
         "posting_id": "10", 
         "posting_title": "dasd", 
         "photo_img": "images/posting/IMG_121212123.png", 
         "normal_price": null 
        } 
       ] 
      } 

     you said that 
     JsonResponse jsonObjList = googleJson.fromJson(jsonArr, JsonResponse .class); 


     But we have two array in data set class right which "jsonArr" we pass for parsing. 

     to get each of separate response of array in log. 

     My data set class 




     public class BannerAdvertismentVO implements Serializable { 

      private ArrayList<NormalPostingVO> promotion_listing; 


      private ArrayList<NormalPostingVO> latest_posting ; 


      public ArrayList<NormalPostingVO> getPromotion_listing() { 
       return promotion_listing; 
      } 


      public void setPromotion_listing(ArrayList<NormalPostingVO> promotion_listing) { 
       this.promotion_listing = promotion_listing; 
      } 


      public ArrayList<NormalPostingVO> getLatest_posting() { 
       return latest_posting; 
      } 


      public void setLatest_posting(ArrayList<NormalPostingVO> latest_posting) { 
       this.latest_posting = latest_posting; 
      } 



     } 





private String posting_id; 
    private String posting_title; 
    private String photo_img; 
    private String normal_price; 



    public String getPosting_id() { 
     return posting_id; 
    } 
    public void setPosting_id(String posting_id) { 
     this.posting_id = posting_id; 
    } 
    public String getPosting_title() { 
     return posting_title; 
    } 
    public void setPosting_title(String posting_title) { 
     this.posting_title = posting_title; 
    } 
    public String getNormal_price() { 
     return normal_price; 
    } 
    public void setNormal_price(String normal_price) { 
     this.normal_price = normal_price; 
    } 
    public String getPhoto_img() { 
     return photo_img; 
    } 
    public void setPhoto_img(String photo_img) { 
     this.photo_img = photo_img; 
    } 
    my parser class 

    public static BannerAdvertismentVO parseBannerAdvertismentData(String response){ 

      BannerAdvertismentVO banner =null; 
      Gson Json; 

      try { 
       JSONObject jsonObject = new JSONObject(response); 

       Json = new GsonBuilder().create(); 

       banner = Json.fromJson(jsonObject.toString(), BannerAdvertismentVO .class); 

       Log.e("", "LOG1==" + banner.getLatest_posting() +"/n"+ banner.getPromotion_listing()); 



      } catch (Exception e) { 
       e.printStackTrace(); 
      } 




      return banner; 
     } 

this show me null->banner.getPromotion_listing(); 
같은 데이터를 얻을 수