2012-09-04 3 views
0

저는 매일 안드로이드 개발과 json 코드에 대해 조금 배우고 있습니다. 하지만 지금은 이것에 붙어 있어요; 온라인 데이터베이스에서 값을 가져 와서 보여줄 수 있지만 전체 json 코드를 볼 수 있습니다. 그리고 내가 보여주고 싶은 부분 만보고 싶습니다. android : json 객체 또는 배열을 만드시겠습니까?

내 코드, 난 정말 기본입니다하지만 난 그냥 웹 페이지에서 값을 받고 내 텍스트 뷰에 넣어거야 볼 수 있듯이 나는 또한

: 배우고 생각하지만, 나는 것 JSONObject 또는 JSONArray에 넣으려면 마녀를 잘 모르는 것이 좋습니다.

누군가 제발 도와 줄 수 있습니까? 종류와

는 정말 하나가 더있는 질문이 아니다

public class Bordje extends Activity{ 

public void onCreate (Bundle savedInstanceState) { 
    try 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.bordje); 

     //This is out textview element, obtained by id from XML Layout 
     TextView myListView = (TextView)findViewById(R.id.netResult2); 

     //Lets connect to the internet 
     try { 
      String result = ""; 
      //create new client object 
      HttpClient httpclient = new DefaultHttpClient(); 
      //now post to the url 
      HttpPost httppost = new HttpPost("http://www.wvvzondag2.nl/android/leesbordje.php"); 
      //execute url 
      HttpResponse response = httpclient.execute(httppost); 
      //get message from the response 
      HttpEntity entity = response.getEntity(); 
      //get the content from message 
      InputStream webs = entity.getContent(); 

      //convert response to string 
      try{ 
       BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"),8); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) { 
         sb.append(line + "\n"); 
       } 
       //slow our inputstream 
       webs.close(); 
       //puts the resut into a string 
       result=sb.toString(); 
      }catch(Exception e){ 
       Log.e("log_tag", "Error converting result "+e.toString()); 
      } 

      //Parsing the JSON Data 
      try{ 
       JSONArray jArray = new JSONArray(result); 
       for(int i=0;i<jArray.length();i++){ 
         JSONObject json_data = jArray.getJSONObject(i); 
         json_data.getString("introtext"); 
         //Get an output to the screen 
         //then here should be some code that displays text? 
         //myListView.setText(Html.fromHtml(json_data)); ? 
       } 

      }catch(JSONException e){ 
        Log.e("log_tag", "Error parsing data "+e.toString()); 
      } 

     }catch(Exception e){ 
      Log.e("log_tag", "Error in http connection"+e.toString()); 
     } 

    } 
    catch (Exception e) 
    { 
     //this is the line of code that sends a real error message to the log 
     Log.e("ERROR", "ERROR IN CODE: " + e.toString()); 
    } 
} 
+0

사이트에 가서 전체 데이터 세트를 제공하고 거기에서 파싱을 원하십니까? 구문 분석 할 데이터를 사용하려고합니까? 그렇지 않은 경우 1) 필요하지 않은 데이터 노출 (데이터가 노출되지 않아야하는 경우 보안 위험이 발생할 수 있음) 2) 많은 대역폭 요구 사항 (웹 서버가 더 많은 데이터를 내보내고 있습니다. 사용자는 더 많은 데이터를 사용하여이를 소비해야합니다. http://federmanscripts.com/2010/12/12/php-routing/이 관심의 대상이 될 수 있습니다 (PHP 사용자가 아니기 때문에 품질에 대해서는 확신 할 수 없지만 최소한 라우팅에 대해서는 다룹니다). – Robert

답변

2

을 간주한다. JSON 객체와 JSON 배열은 서로 다른 두 가지 기능을합니다.

JSON 배열은 (like) 항목 (http://www.json.org/javadoc/org/json/JSONArray.html)의 정렬 된 순서입니다.

JSONArray jsonArray = new JSONArray("[JSON TEXT]"); 
String textToDisplay = jsonArray.getString(index); //return String at index 

JSON 객체가 맵 (http://www.json.org/javadoc/org/json/JSONObject.html).

JSONObject jsonObj = new JSONObject("[JSON TEXT]"); 
String textToDisplay = jsonObj.getString("key"); //returns String value 

그런 다음 데이터를받은 후에는 이전과 같이 텍스트보기에서 설정하십시오. 당신은 서버에서 유효한 JSON을 받고있는 경우

myListView.setText(textToDisplay); 
+0

먼저 빠른 답장을 보내 주셔서 감사합니다. 코드 조각을 추가했습니다. 하지만 데이터를 표시하는 데 더 많은 것을 넣어야합니다. –

+1

루프에서 으로 전화하십시오. json_data.getString ("introtext"); 변수에 반환 된 문자열을 할당하지 않습니다. 내 업데이트 된 응답을 참조하십시오. 배열의 모든 항목에 대해이 값을 가져와야하는 경우 루프의 텍스트를 연결하고 setText (fullString)를 호출해야합니다. 말이 돼? – loeschg

+0

예. 이해가됩니다. 도움을 주셔서 감사합니다. D –

0

당신은 단순히 그 객체는 점점 그래서 하나가 더 나은 말의 아무 소용이 없습니다에 따라 JSONArray 또는 그 JSONObject을 만들 수 있습니다. 그러나 귀하의 경우에는 아마 JSONArray가 될 것입니다.

잘 실현하려면 gson을 사용하여 유효한 json 문자열을 JSONObject 또는 JSONArray으로 변환 할 수 있습니다.

.toJson().fromJSON(object) 방법으로 작업하게됩니다.

관련 문제