2011-01-18 3 views
3

친구, 주어진 URL에서 직접 json 콘텐츠를 파싱하는 데 문제가 있습니다. 그러나 내 res/raw 폴더의 텍스트 파일과 동일한 URL 콘텐츠를 저장할 때 다음과 같이 데이터를 구문 분석합니다. 인터넷에서 URL의 컨텐츠를 가져 오는 경우도 있지만, 시작 (예) JSONArray 텍스트는 반드시 예외를 보여줍니다 '['의 문자 하나 ... 내가이 문제를 해결하는 잘못된 here.help가 무엇JSON이 Android 용 URL 콘텐츠를 가져옵니다.

에서 문제


URL url_net = new URL("http://samplejson.com/transactions.json"); 
InputStream is = url_net.openStream(); 
byte [] buffer = new byte[is.available()]; 
while (is.read(buffer) != -1); 
String jsontext = new String(buffer); 
JSONArray entries = new JSONArray(jsontext); 
x = "JSON parsed.\nThere are [" + entries.length() + "]\n\n"; 
int i; 
for (i=0;i<entries.length();i++) { } 
+0

OK : 여기

내가하는 HTTP GET의 문자열 콘텐츠를 얻기 위해 사용하는 코드입니다. JSON 자체를 살펴 보았지만 괜찮았다. – Aliostad

+0

URL url_net = 새 URL ("http://184.106.227.45/quaddeals/university-of-illinois/androids/transactions/type:available/752/transactions.json"); \t \t InputStream is = url_net.openStream(); \t \t 바이트 [] 버퍼 = 새 바이트 [is.available()]; \t \t while (is.read (buffer)! = -1); \t \t 문자열 jsontext = new 문자열 (버퍼); \t \t JSONArray 항목 = 새 JSONArray (jsontext); \t \t \t \t x = "JSON 구문 분석. \ n ["+ entries.length() + "] \ n \ n"; \t \t \t int i; \t \t (i = 0; i

답변

10

OK, 코드가 헤더를 포함한 모든 HTTP를 읽는 것 같습니다. 그래서 당신의 "["로 시작하지 않습니다. 당신이 HTTP에서 텍스트를 얻고 JSON을로드 할 수있는 코드를 게시,

public static String getStringContent(String uri) throws Exception { 

    try { 
     HttpClient client = new DefaultHttpClient(); 
     HttpGet request = new HttpGet(); 
     request.setURI(new URI(uri)); 
     HttpResponse response = client.execute(request); 
     InputStream ips = response.getEntity().getContent(); 
     BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8")); 

     StringBuilder sb = new StringBuilder(); 
     String s; 
     while(true) 
     { 
      s = buf.readLine(); 
      if(s==null || s.length()==0) 
       break; 
      sb.append(s); 

     } 
     buf.close(); 
     ips.close(); 
     return sb.toString(); 

     } 
    finally { 
       // any cleanup code... 
      } 
     } 
+0

HTTP 페이로드를 참조하는 response.getEntity() .getContent()에 주목하십시오. – Aliostad

+10

더 깨끗한 접근법은'String content = client.execute (request, new BasicResponseHandler())'를 사용하여 12 행을 절약하는 것입니다. – Dave

+0

Thanks Dave. BasicResponseHandler()를 인식하지 못했습니다. – Aliostad

관련 문제