2013-03-11 1 views
1

last.fm 웹 서비스를 사용하여 앨범을 검색하는 iOS 앱을 작성하고 있습니다. 다음 코드는있는 NSArray에 반환 된 JSON 변환 : 검색어가 결과를 반환 할 때이 잘 작동last.fm에 키가 있는지 확인하십시오. json이 반환되었습니다.

results = (NSArray *)[[[json valueForKey:@"results"] valueForKey:@"albummatches"] valueForKey:@"album"]; 

하지만, 응용 프로그램이 충돌이 더 결과가 반환되지 않은 경우. 이것은 "앨범"키가 결과가 없을 때 json에 존재하지 않기 때문입니다.

"앨범"키가 json에 있는지 확인하려면 어떻게 신청합니까?

편집 : 결과가 없을 때 샘플 json이 반환됩니다. 검색 문자열은 'asdfgasdfg'입니다. albummatches 키 아래의 문자 반환을 확인하십시오.

2013-03-12 14:08:00.889 MyMusicLibrary[387:1a03] { 
results =  { 
    "@attr" =   { 
     for = asdfgasdfg; 
    }; 
    albummatches = "\n"; 
    "opensearch:Query" =   { 
     "#text" = ""; 
     role = request; 
     searchTerms = asdfgasdfg; 
     startPage = 1; 
    }; 
    "opensearch:itemsPerPage" = 50; 
    "opensearch:startIndex" = 0; 
    "opensearch:totalResults" = 0; 
}; 
} 

편집 2 : 샘플 JSON 결과가 반환됩니다

2013-03-12 14:19:42.769 MyMusicLibrary[880:1a03] { 
results =  { 
    "@attr" =   { 
     for = coldplay; 
    }; 
    albummatches =   { 
     album =    (
          { 
       artist = Coldplay; 
       id = 1416655; 
       image =      (
              { 
         "#text" = "http://userserve-ak.last.fm/serve/34s/85845017.png"; 
         size = small; 
        }, 
              { 
         "#text" = "http://userserve-ak.last.fm/serve/64s/85845017.png"; 
         size = medium; 
        }, 
              { 
         "#text" = "http://userserve-ak.last.fm/serve/126/85845017.png"; 
         size = large; 
        }, 
              { 
         "#text" = "http://userserve-ak.last.fm/serve/300x300/85845017.png"; 
         size = extralarge; 
        } 
       ); 
       mbid = "c67be398-9417-4c22-bc13-d6158029ae21"; 
       name = "A Rush of Blood to the Head"; 
       streamable = 1; 
       url = "http://www.last.fm/music/Coldplay/A+Rush+of+Blood+to+the+Head"; 
      }, 
          { 
       artist = Coldplay; 
       id = 1984; 
       image =      (
              { 
         "#text" = "http://userserve-ak.last.fm/serve/34s/87203265.png"; 
         size = small; 
        }, 
              { 
         "#text" = "http://userserve-ak.last.fm/serve/64s/87203265.png"; 
         size = medium; 
        }, 
              { 
         "#text" = "http://userserve-ak.last.fm/serve/126/87203265.png"; 
         size = large; 
        }, 
              { 
         "#text" = "http://userserve-ak.last.fm/serve/300x300/87203265.png"; 
         size = extralarge; 
        } 
       ); 
       mbid = "8e602038-c0f2-3c2d-9068-a1a3daca493d"; 
       name = Parachutes; 
       streamable = 1; 
       url = "http://www.last.fm/music/Coldplay/Parachutes"; 
      } 
     ); 
    }; 
    "opensearch:Query" =   { 
     "#text" = ""; 
     role = request; 
     searchTerms = coldplay; 
     startPage = 1; 
    }; 
    "opensearch:itemsPerPage" = 2; 
    "opensearch:startIndex" = 0; 
    "opensearch:totalResults" = 375; 
}; 
} 
+0

결과 키가 항상 있다고 가정합니다. 그러나 그것보다 당신이 nil 객체에 대한 메소드를 호출한다면 – giorashc

+0

그 결과는 항상 배열이며, 배열이 아닌 것에 메시지를 보내려고합니다. –

+0

작동하는 JSON의 NSLog를 제공 할 수 있습니까? –

답변

1

당신이 "opensearch:totalResults" 올바른 결과가 결과가있을 경우 결정하기 위해이 값을 사용할 수 있습니다 다음 계산 사실이라고 가정이

  1. 에 대한 이동 여부를 다음 수있는 두 가지 방법이 있습니다 당신이 문자열이나 배열을 가지고 있는지 그것을

    을 처리하기 전에

    NSArray *results = nil; 
    
    if ([[json valueForKeyPath:@"results.opensearch:totalResults"] intValue] > 0) { 
        results = [json valueForKeyPath:@"results.albummatches.album"]; 
    } 
    
  2. 확인을 사용

    id albummatches = [json valueForKeyPath:@"results.albummatches"]; 
    
    // is this a dictionary or a string? 
    // You can either ask if it implements the interface or ask what class it is. I prefer the first 
    BOOL isDictionary = [albummatches respondsToSelector:@selector(objectForKey:)]; 
    
    // or 
    BOOL isDictionary = [albummatches isKindOfClass:[NSDictionary class]]; 
    
    if (isDictionary) { 
        results = [albummatches objectForKey:@"album"]; 
    } 
    
+0

옵션 1이 완벽하게 작동했습니다. 이걸 도와 주셔서 감사합니다. – Cheese1223

0

확인 :

if([[json[@"result"][@"albummatches"] allKeys] containsObject:@"album"]==YES){ 

    //do your work here 
} 
0

누군가가 정말 좋은 답변 이전에 게시 있지만 다음 제거되었다. 그것은 이것으로 많은 도움이되었고, 아래 코드를 얻기 위해 약간 수정했습니다. 현재 작동합니다.

  NSDictionary *resultsDict = [json valueForKey:@"results"]; 
     if (resultsDict != nil) { 
      //Checks to see if any results are returned 
      NSDictionary *albumMatchesDict = [resultsDict valueForKey:@"albummatches"]; 
      NSString *albumMatchesString = [resultsDict valueForKey:@"albummatches"]; 
      NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet]; 
      albumMatchesString = [[albumMatchesString description] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; 

      if ([[albumMatchesString stringByTrimmingCharactersInSet:set] length] != 0) { 
       results = (NSArray *) [albumMatchesDict valueForKey:@"album"]; 
      } 
     } 
+0

이것은 실제로 나쁜 구현입니다. 실제 JSON을 제공 할 수 있고 누군가가 올바르게 수행 할 수있는 방법을 보여줄 수 있습니다. 사전에 액세스하기 위해 위의 많은 불필요한 코드가 있습니다. 그 다음 배열/사전의 문자열 표현에 대한 조작을 수행 한 결과를 확인하십시오. 특히 나중에 시간이 걸리지 않을 경우에 거의 확실하게 나중에 문제가됩니다. 이 코드에 대한 나쁜 점을 이해하고 사방에 다시 구현해야합니다. –

+0

반환 된 json에 결과가없는 경우 albummatches 키 아래에 귀찮은 문자가 반환되기 때문에 내가 그랬던 이유입니다. 위의 질문에 반환 된 결과가없는 json을 게시합니다. – Cheese1223

+0

앨범이 있으면 짧은 스 니펫을 제공 할 수 있습니까? –