2012-04-01 4 views
0

이 JSON 파일을 올바르게 구문 분석하는 방법을 파악하는 데 어려움을 겪고 있습니다.Android JSON API를 사용하여 구문 분석

{ 
    "count": 10, 
    "timestamp": 1333243153, 
    "total": 100, 
    "diggs": [ 
     { 
      "date": 1333243146, 
      "item": { 
       "status": "upcoming", 
       "container": { 
        "name": "Politics", 
        "short_name": "politics" 
       }, 
       "description": "Major steps toward the disestablishment of Norway's state church, the (Lutheran) Church of Norway, were passed by the government on March 16 in its weekly session with King Harald V.", 
       "title": "National Secular Society - Norway continues the long process of disestablishing the Lutheran Church", 
       "submit_date": 1333206325, 
       "media": 0, 
       "diggs": 5, 
       "comments": 0, 
       "topic": { 
        "name": "Politics", 
        "short_name": "politics" 
       }, 
       "shorturl": { 
        "short_url": "http://digg.com/news/politics/national_secular_society_norway_continues_the_long_process_of_disestablishing_the_lutheran_church", 
        "view_count": 0 
       }, 
       "promote_date": null, 
       "link": "http://www.secularism.org.uk/news/2012/03/norway-continues-the-long-process-of-disestablishing-the-lutheran-church", 
       "href": "http://digg.com/news/politics/national_secular_society_norway_continues_the_long_process_of_disestablishing_the_lutheran_church", 
       "id": "20120331150525:56935e86-2dbf-4831-ad60-50def7781e68" 
      }, 
      "user": { 
       "name": "ghelms", 
       "links": [], 
       "registered": 1158007588, 
       "profileviews": 0, 
       "fullname": "Gary Helms", 
       "icon": "http://cdn2.diggstatic.com/user/614412/l.2001177284.png" 
      }, 
      "digg_id": "20120401011907:5cf92ee9-e915-4358-b14f-cf140b760469" 
     }, 
    ], 
    "offset": 0 
} 

난 단지 요소 "날짜", "설명", "제목", "열심히 잖아요", "링크"및 "digg_id"의 ​​일부를 얻기 위해 노력하고있어. 파싱을 시도 할 때마다 listView에서 작동하지 않습니다. 아무 것도 나타나지 않지만 GetMethod 클래스에서 String을 사용하면 전체 API를 문자열로 구문 분석하여 잘 인쇄합니다.

내 코드 :

public DiggItemList lastDigg() throws Exception { 
    ArrayList<HashMap<String,DiggItem>> diggsList = new ArrayList<HashMap<String, DiggItem>>(); 
    JSONArray diggs = null; 
    JSONObject json = null; 
    Intent in = getIntent(); 
    String short_name = in.getStringExtra(TAG_SHORT_NAME); 
    GetMethod get = new GetMethod(); 
    json = get.getInternetData(); 

    try { 
     diggs = json.getJSONArray("diggs"); 

      dlists = new DiggItemList(); 
      for (int i = 0; i < diggs.length(); i++) { 
       JSONObject c = diggs.getJSONObject(i); 
       String date = c.getString("date"); 
       String description = c.getString("description"); 
       String title = c.getString("title"); 
       int digg = c.getInt("diggs"); 
       String link = c.getString("link"); 
       int digg_id = c.getInt("digg_id"); 

       //JSONObject topic = c.getJSONObject("topic"); 
        //String sn = topic.getString("short_name"); 

       DiggItem di = new DiggItem(); 
       di.setDate(c.getInt("date")); 
       di.setDescription(c.getString("description")); 
       di.setTitle(c.getString("title")); 
       di.setDiggs(c.getInt("diggs")); 
       di.setLink(c.getString("link")); 
       di.setDigg_id(c.getString("digg_id")); 
        dlists.add(di); 
        /* 
       if (sn.equals(short_name)) { 
        dlists.add(di); 
       } 
           */ 
      } 

    }catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return dlists; 
} 

클래스는 API를 얻을 수 있습니다. (http://services.digg.com/2.0/digg.getAll). 저장하는 동안 같은 곳

public class GetMethod { 

    public JSONObject getInternetData() throws Exception { 
     BufferedReader in = null; 
     String data = ""; 
     JSONObject jObj = null; 
     try { 
      HttpClient client = new DefaultHttpClient(); 
      URI website = new URI("http://services.digg.com/2.0/digg.getAll"); 
      HttpGet request = new HttpGet(); 
      request.setURI(website); 
      HttpResponse response = client.execute(request); 
      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
      StringBuffer sb = new StringBuffer(""); 
      String line = ""; 

      while ((line = in.readLine()) != null) { 
        sb.append(line + "\n"); 
      } 
      in.close(); 
      data = sb.toString(); 
     }finally { 
      if (in != null) { 
       try { 
        in.close(); 
       }catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
     try { 
      jObj = new JSONObject(data); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 
    } 
    } 

답변

1

그냥 코드 날짜에 ... 더 자세한 내용은 을 참조하여 튜토리얼을 공부 ... 원하는 문자열 형식을 https://stackoverflow.com/questions/5867544/android-json-parsing-tutorial/9742384#9742384

public void parseData throws Exception { 

      try { 
    HttpClient httpclient = new DefaultHttpClient(); 

       // Prepare a request object 
     HttpGet httpget = new HttpGet("http://services.digg.com/2.0/digg.getAll"); 

       // Execute the request 
       HttpResponse response; 
       // Get hold of the response entity 
        HttpEntity entity = response.getEntity(); 
        // If the response does not enclose an entity, there is no need 
        // to worry about connection release 

        if (entity != null) { 

         // A Simple JSON Response Read 
         // InputStream instream = entity.getContent(); 
         // String result = convertStreamToString(instream).trim(); 

         String result = EntityUtils.toString(entity); 
    JsonObject json = new JsonObject(result); 

    JSONArray diggsJsonArray = json.getJSONArray("diggs"); 

    for(int i =0;i<diggsJsonArray.length;i++) 
    { 
    JsonObject individualDiggsObj = diggsJsonArray.getJSONObject(i); 

     DiggItem di = new DiggItem(); 
        di.setDate(individualDiggsObj.getInt("date")); 
    di.setDiggId(individualDiggsObj.getString("digg_id")); 
    JSONOnejct itesmJson = new JSONOBJECT(individualDiggsObjgetJSONObject("item"); 

    //NOw Fetch and Set the values of status,title,description,, etc from the itemsJson to your collection. 

    //Similarly begin with other inner Array's and Object's if available. 
       }catch(Exception e) 
    { 
    e.printStackTrace(); 
     } 
0

을 할 수있는 간단한 방법을 제안 "DiggItem di"에서 정수 값인 c.getInt ("date")를 사용하고 있습니다. digg_id의 값이 영숫자의 조합이기 때문에 digg_id는 정수가 될 수 없으므로 여기서도 String을 사용할 수 있습니다.