2012-07-18 6 views
0

서버에서 JSON 응답을 다시 가져 오는 중이고 필요한 배열은 여러 개체와 배열 내부 깊숙이 포함 된 값입니다. formatIds JSONArray를 가져와야합니다. 내 JSON은 다음과 같습니다 때문에 모두의여러 개체/배열 안에 JSONArray 가져 오기

String[] assetUri; 
for (int i = 0; i < entriesArray.length(); i++) { 
    entryJsonOjbect = entriesArray.getJSONObject(i); 
    fileTargetArray = tempObj.getJSONArray("targets"); 
    //Loop through the targets array 
    for (int j = 0; j < fileTargetArray.length(); j++) { 
     tempObj = fileTargetArray.getJSONObject(j); 
     fileCriteriaArray = tempObj.getJSONArray("formatCriteria"); 
     //Loop through fileCriteria Array 
     for (int h = 0; h < fileCriteriaArray.length(); h++) { 
      JSONObject fileCriteriaObj = fileCriteriaArray.getJSONObject(h); 
      //Get the JSON Object 'formatSteps' 
      JSONObject selectStepObj = fileCriteriaObj.getJSONObject("formatSteps"); 
      //Get the JSON Object 'formatMatches' 
      JSONObject selectionMatches = selectStepObj.getJSONObject("formatMatches"); 
      //FINALLY. Get the formatIds ARray 
      JSONArray assetTypeArray = selectionMatches.getJSONArray("formatIds"); 
       //Assign the values from the JSONArray to my class 
       assetUri = new String[assetTypeArray.length()]; 
       for (int z = 0; z < assetTypeArray.length(); z++) { 
        assetUri[z] = assetTypeArray.getString(z); 
      } 

     } 
    } 
} 

이 코드는 정말 정말 느린 X20 :

{ 
    "entries": [ 
     { 
      "title": "sample", 
      "targets": [ 
       { 
        "format": "wav",`enter code here` 
        "description": "A wav file", 
        "formatCriteria": [ 
         { 
          "formatSelectionTitle": "Find WAV files", 
          "formatSteps": { 
           "UniqueId": "214212312321", 
           "formatMatches": { 
            "formatIds": [ 
             "WAV", 
             "MP3" 
            ] 
           } 
          } 
         } 
        ] 
       } 
      ] 
     } 
    ] 
} 

내가 알아낼 수 있었던 유일한 방법은 루프를 내장 한 무리를하는 것입니다 내장 된 루프. 이 여분의 코드가 없어도이 JSONArray를 얻을 수있는 방법이 있습니까 ?? jQuery에는 JSON.find이 있으며 Java에서 이와 비슷한 것이 있는지 궁금합니다. getJSONArray은 jsonObject 루트에을 가져 오지만 json 배열이있는 객체에 있지 않으면 작동하지 않습니다. 내가 재귀 솔루션의 몇 가지 유형을 할 수 확신하지만, 이것은 여전히 ​​성가신입니다. 어떤 충고??

답변

1

org.json 라이브러리로 JSON을 구문 분석하는 것은 DOM을 사용하여 XML을 구문 분석하는 것과 같습니다. 하지만 :이 모든 루프가 필요할 것입니다.

게시 한 JSON 응답 (모든 배열의 단일 요소)과 항상 비슷한 경우 JSON이 매우 효과적입니다. "첫 번째"항목 만 원할 경우 배열을 반복하지 마십시오.

이러한 복잡한 데이터 구조를 org.json으로 구문 분석하는 것은 어려울 수 있습니다. (자동화 된) google-gson 라이브러리를 사용해 보셨습니까? the examples을 확인하십시오. gson으로 파싱하는 것이 CPU 시간면에서 더 빠를 것이라고 말하고 싶지는 않지만 개발 시간면에서 부족합니다.

는 또한 최근에이 주제에 대한 블로그 게시물을 작성한 사람 : JSON and Java

관련 문제