2012-08-30 4 views
0

나는 스포츠 개체 우리가 겪고있는json 비슷한 내부 개체를 구문 분석하는 방법?

{"sports" :[{"name" :"baseball","id" :1,"links" :{"api" :{"sports" :{"href" :"http://api.espn.com/v1/sports/baseball"},"news" :{"href" :"http://api.espn.com/v1/sports/baseball/news"},"notes" :{"href" :"http://api.espn.com/v1/sports/baseball/news/notes"},"headlines" :{"href" :"http://api.espn.com/v1/sports/baseball/news/headlines"},"events" :{"href" :"http://api.espn.com/v1/sports/baseball/events"}}},"leagues" :[{"name" :"Major League Baseball","abbreviation" :"mlb","id" :10,"groupId" :9,"shortName" :"MLB","season" :{"year" :2012,"type" :2,"description" :"regular","startDate" :"2012-03-27T19:00:00Z","endDate" :"2012-10-05T06:59:59Z"},"week" :{"number" :23,"startDate" :"2012-08-28T19:00:00Z","endDate" :"2012-09-04T18:59:00Z"}}]}],"timestamp" :"2012-08-30T18:01:29Z","status" :"success"} 

내가 JSON 개체를 구문 분석하려면 다음 코드를, 데 또 다른 스포츠 요소의 배열 내부 JSON 개체를 구문 분석하는 방법을 객체.

나는 다음과 같은 코드로 노력하고 있어요 : 내가 좀 도와주세요 어떤 출력이없는 내부 개체를 구문 분석 할 때

public class BaseballActivity extends ListActivity{ 

private static String url = "http://api.espn.com/v1/sports/baseball?apikey=h29yphwtf7893hktfbn7cd5g"; 

private static final String TAG_SPORTS = "sports"; 
private static final String TAG_ID = "id"; 
private static final String TAG_TIMESTAMP = "timestamp"; 
private static final String TAG_NAME = "name"; 
private static final String TAG_NEWS = "news"; 
private static final String TAG_HEADLINES = "headlines"; 
private static final String TAG_LINKS = "links"; 
private static final String TAG_API = "api"; 
private static final String TAG_SPORTS1 = "sports"; 
private static final String TAG_HREF = "href"; 

JSONArray sports = null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 


    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    // HashMap for ListView 

    ArrayList<HashMap<String, String>> sportsList = new ArrayList<HashMap<String, String>>(); 

    // creating Json parser instance 
    JSONParser jParser = new JSONParser(); 

    // getting Json String from url 

    JSONObject json = jParser.getJSONFromUrl(url); 

    try{ 
     // Getting Array of Contacts 
        sports = json.getJSONArray(TAG_SPORTS); 

        // looping through All Contacts 
        for(int i = 0; i < sports.length(); i++){ 
         JSONObject c = sports.getJSONObject(i); 


      //String news = c.getString(TAG_NEWS); 
      // String headlines = c.getString(TAG_HEADLINES); 
      String name = c.getString(TAG_NAME); 
      // String timestamp = c.getString(TAG_TIMESTAMP); 
      String id = c.getString(TAG_ID); 

     // JSONObject links = c.getJSONObject(TAG_LINKS); 
      // JSONObject api = c.getJSONObject(TAG_API); 
      // JSONObject sports = c.getJSONObject(TAG_SPORTS1); 

     // String href = c.getString(TAG_HREF); 



      HashMap<String, String> map = new HashMap<String, String>(); 

     // map.put(TAG_TIMESTAMP, timestamp); 
      map.put(TAG_NAME, name); 
      // map.put(TAG_NEWS, news); 
      // map.put(TAG_HEADLINES, headlines); 
      map.put(TAG_ID, id); 
     // map.put(TAG_HREF, href); 
      sportsList.add(map); 
     } 
    } 
     catch (JSONException e) { 
      e.printStackTrace();  

     } 


    ListAdapter adapter = new SimpleAdapter(this, sportsList, 
      R.layout.list_item, 
      new String[]{TAG_NAME,TAG_ID} , new int[] { 
      R.id.id,R.id.name}); 

setListAdapter(adapter); 
}} 



ublic class JSONParser { 

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 

public JSONObject getJSONFromUrl(String url) { 

    // Making HTTP request 
    try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent();   

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return jObj; 
}} 

이름과 ID를 표시 할 수 있습니다.

답변

1

당신은 당신이

된 JSONObject하는 jobject는 = 새로운 된 JSONObject (JSON)에 대한 작업을 수행해야이보다 당신의 JSON 문자열

에 오는 개체가 그 클래스 스포츠를해야한다; jObject.getJSONObject ("sports"); 당신이) 새 GSON (다음

GSON의 GSON =을 할 구글의 GSON 라이브러리를 사용하는 것보다

이 당신의 JsonString 노출되어 내부 단자부 된 JSONObject를 만들 것입니다; 스포츠 스포츠 = gson.fromJson (jObject.toString(), Sports.class);

나는, 유 Activitys 프로젝트가 더 구조화하게하고 코드가

+0

당신이 샘플 코드 또는 링크를 좀 도와주십시오 수 있습니다 청소기하게 될에이 코드가 모든 WebReqeuisitions을 처리하지하는 클래스가 조언 나는 안드로이드를 처음 사용합니다. – srikanth

+0

은 googles Gson을 사용하기위한 문서입니다. http://code.google.com/p/google-gson/ && 여기에 Json http://www.json.org/의 사이트가 있지만 if 내가 위 단계에서 말한 단계는 트릭을해야한다. –

+0

ok, 시도해 보겠다. – srikanth

관련 문제