Looking for an object in a nested NSDictionary when the parent key is unknown?

I am using the yajl_JSON library to create an NSDictionary from a JSON response for the bit.ly url shortening service.

JSON answer:

{
  errorCode = 0;
  errorMessage = "";
  results = {
      "http://www.example.com/" = {
          hash = 4H5keM;
          shortKeywordUrl = "";
          shortUrl = "http://bit.ly/4BN4qV";
          userHash = 4BN4qV;
      };
  };
  statusCode = OK;
}

To clarify, http://example.com β€œis not a child of theβ€œ result. "And when I figure it out, I have 3 three nested NSDictionaries.

The problem is that " http://example.com " is an arbitrary key. I want to access key data without knowing the key. In particular, therefore, I can get the value for "shortUrl". How can this be done effectively? Is there a way to make keyPath this way:

"results.*.shortUrl"

I accomplished this by doing the following, but I believe that this is not how it is done:

 // Parse the JSON responce
 NSDictionary *jsonResponce = [data yajl_JSON];

 // Find the missing key
 NSString *missingKey = [[[jsonResponce valueForKeyPath:@"results"] allKeys] objectAtIndex:0];

 // Log the value for "shortURL"
 NSLog(@"It is : %@", [[[jsonResponce objectForKey:@"results"] valueForKeyPath:missingKey] objectForKey:@"shortUrl"]);

XML, , , json/ objective-c.

, "example.com" , Bit.ly, ... ...

.

+3
2

NSDictionary allValues , , Key-Value Coding NSArrays . , [[jsonResponse valueForKeyPath:@"results.allValues.shortURL"] objectAtIndex:0], shortURL.

+4

, NSDictionary results = [jsonResponce objectForKey:@"results], :

{
    "http://www.example.com/" = {
          hash = 4H5keM;
          shortKeywordUrl = "";
          shortUrl = "http://bit.ly/4BN4qV";
          userHash = 4BN4qV;
    };
};

:

NSString *shortURL = null;
for (id key in results) {
    NSDictionary* resultDict = [results objectForKey:key];
    shortURL = [resultDict objectForKey:@"shortURL"];
    NSLog(@"url: %@ shortURL: %@", key, shortURL);
}

:

NSDictionary* resultDict = [[results allValues] objectAtIndex:0];
NSString *shortURL = [resultDict objectForKey:@"shortURL"];

, URL-, allKeys:

NSString *url = [[results allKeys] objectAtIndex:0]
NSDictionary* resultDict = [results objectForKey:url];
NSString *shortURL = [resultDict objectForKey:@"shortURL"];

( , , allKeys allValues.)

+2

Source: https://habr.com/ru/post/1725966/


All Articles