2011-05-03 4 views
4

URL에서 JSON 응답을 구문 분석하고 싶지만 항상 오류가 있습니다. 나는 너무 많이 시도했지만 문제를 해결하지 못했습니다. 오류를 바로 잡으라고 제안 해주세요.android에서 큰 JSON 파일을 구문 분석하는 방법

내 JSON 응답 :

{ 
"classification": { 
    "relevancyScore": 999, 
    "searchUrl": { 
     "value": "http://www.bizrate.com/iphone-cases/index__rf--af1__af_assettype_id--10__af_creative_id--6__af_id--50085__af_placement_id--1.html" 
    } 
}, 
[.. hundreds of lines removed ..] 

내 코드 : 나는 모든 제품의 정보를 분석해야

public class test extends Activity { 

    /** Called when the activity is first created. */ 
    @SuppressWarnings({ "rawtypes", "unchecked" }) 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     ListView lv = (ListView)findViewById(R.id.listView1); 

     lv.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));   
    } 

    public ArrayList<String> fetchTwitterPublicTimeline() 
    { 
     ArrayList<String> listItems = new ArrayList<String>(); 

     try { 
      URL twitter = new URL(
        "http://catalog.bizrate.com/services/catalog/v1/us/product?publisherId=50085&placementId=1&categoryId=1&keyword=iphone+cases&start=0&results=10&sort=relevancy_desc&brandId=&attFilter=&zipCode=90291&biddedOnly=&minRelevancyScore=100&apiKey=58f536aa2fab110bbe0da501150bac1e&format=json"); 
      URLConnection tc = twitter.openConnection(); 
      BufferedReader in = new BufferedReader(new InputStreamReader(
        tc.getInputStream())); 

      String line; 
      String str; 
      while ((line = in.readLine()) != null) { 
       //str = line.substring(line.indexOf("{"), line.lastIndexOf(line)); 
       //str = line.replaceAll("BIZRATE.Suggest.callback(", null); 
       //str = str.replaceAll(")", null); 
       //System.out.println("SubString:"+str); 
       JSONArray ja = new JSONArray(line); 

       for (int i = 0; i < ja.length(); i++) { 
        JSONObject jo = (JSONObject) ja.get(i); 
        System.out.println("value----"+jo.getJSONObject("product")); 
        //listItems.add(jo.getString("suggestions")); 
       } 
      } 
     } catch (MalformedURLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return listItems; 
    } 
} 

.

+3

어떤 오류가 발생합니까? JSONArray로 각 행을 파싱하는 이유는 무엇입니까? 행이 실제로 배열인지 확인할 수 있습니까? – alopix

답변

1

당신은 전에 전체 JSON을 다운로드해야합니다 ... 그것은 ... 위하여 표준화 방식으로 데이터를 가져 예를 들어 그것을 시도 .. JSON에서 데이터를 가져 오기 위해 오픈 API Gson.jar을 사용할 수 있습니다 그것을 파싱 할 수 있습니다. 이 프로젝트에서 당신을 도움이 될 것입니다 당신이 키 존재한다 란 확실히 모르는 경우

try { 
    URL twitter = new URL("http://catalog.bizrate.com/services/catalog/v1/us/product?publisherId=50085&placementId=1&categoryId=1&keyword=iphone+cases&start=0&results=10&sort=relevancy_desc&brandId=&attFilter=&zipCode=90291&biddedOnly=&minRelevancyScore=100&apiKey=58f536aa2fab110bbe0da501150bac1e&format=json"); 
    URLConnection tc = twitter.openConnection(); 
    BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream())); 
    String line; 
    String str = ""; 
    while ((line = in.readLine()) != null) { 
     str += line; 
    } 
    JSONObject jo = new JSONObject(str); 
    JSONArray ja = jo.getJSONObject("products").getJSONArray("product"); 
    for (int i = 0; i < ja.length(); i++) { 
     Log.i("MyDebug", "value----" + ja.getJSONObject(i).getString("manufacturer")); 
    } 
} catch (MalformedURLException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (JSONException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

has("") 작업을해야합니다.

2

서버의 큰 JSON 파일이있는 경우 gson 파서를 사용하는 것이 더 좋습니다. 큰 JSON을 읽는 동안 메모리 오류가 발생했습니다. JSON은 먼저 데이터를 구문 분석하는 메모리로로드하기 때문에. 그래서 메모리 예외를 벗어나는 변화가있을 수 있습니다.

관련 문제