2012-09-26 2 views
-3

JSON 구문 분석을 처음 시도했습니다. 내 JSON 데이터에는 단일 JSON 배열에 여러 JSON 객체가 있습니다. 데이터 샘플 :Android에서 JSON의 여러 값을 구문 분석하는 방법은 무엇입니까?

{ "루트": [ "Sc_we": []}, { "Sc_wesam": "{머리": "시작 페이지"}, { "색상" 나는 위의 JSON 데이터를 가져

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    try { 
     website = new URL(
        "http://xxxxxxx"); 
     InputStream in = website.openStream(); 
     parseMovie(in); 
    } 
    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(); 
    } 
} 


protected void parseMovie(InputStream json) throws IOException, 
JSONException { 
    // TODO Auto-generated method stub 

    BufferedReader reader = new BufferedReader(new InputStreamReader(json)); 
    StringBuilder sb = new StringBuilder(); 
    String line = reader.readLine(); 
    while (line != null) { 
     sb.append(line); 
     line = reader.readLine(); 
    } 
    reader.close(); 
    System.out.println(sb); 
    JSONObject jobj = new JSONObject(sb.toString()); 
    System.out.println("jsonobj:" + jobj); 

    JSONArray array = jobj.getJSONArray("root"); 

    System.out 
     .println("jsonobject :+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" 
       + array); 
} 

,하지만 난 S_we 값과 Sc_wesam 데이터가 필요 :}]}]}

이 내 코드입니다.

어떻게하면됩니까?

답변

3

당신은 당신의 JSONArray를 사용하여 개별 요소를 반복하고 데이터에 대한 몇 가지 가정 할 수 있습니다 : 난 내 JSON에서 두 개 이상의이 (가)에 대한 더 많은 두 개의 OBJ이다 arraor 경우

JSONArray array = jobj.getJSONArray("root"); 
JSONObject subObj; 
JSONArray subArray; 

for (int i = 0; i < array.length(); i++) 
{ 
    subObj = array.getJSONObject(i); 

    if (subObj.has("Sc_wesam")) // handle Se_wesam 
    { 
     subArray = subObj.getJSONArray("Sc_wesam"); 

     for (int j = 0; j < subArray.length(); j++) 
     { 
      subObj = subArray.getJSONObject(j); 
      if (subObj.has("head")) 
       System.out.println("Sc_wesam head value: " + 
            subObj.getString("head")); 
      else if (subObj.has("color")) 
       System.out.println("Sc_wesam color value: " + 
            subObj.getString("color")); 
     } 
    } 
    else if (subObj.has("Sc_we")) // handle Se_we 
    { 
     subArray = subObj.getJSONArray("Sc_wesam"); 

     // ... etc. 
    } 
} 
+0

답을 가지고 있지만, 무엇을 내 링크를 어떻게해야합니까. 어떤 방법으로 도와 주셔서 감사합니다 – Ramz

+1

@Ramz 코드는 배열의 모든 하위 객체를 반복합니다. 그러나 데이터에 대해 더 많은 가정을해야 할 수도 있습니다. 즉, 더 많은 이름을 찾으십시오. _Sc_we_ 및 _Sc_wesam_. 결과가 어떻게 보이길 원하는지에 달려 있습니다. JSON 구조를 완전히 파싱 하시겠습니까, 아니면 JSON 구조의 일부만 꺼내시겠습니까? – pb2q

관련 문제