6

I have the following JSON object:

{
"response": {
    "status": 200
},
"messages": [
    {
        "message": {
            "user": "value"
            "pass": "value",
            "url": "value"
         }
 ]
    }

}

I am using JSON-Framework (also tried JSON Touch) to parse through this and create a dictionary. I want to access the "message" block and pull out the "user", "pass" and "url" values.

In Obj-C I have the following code:

// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];

// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:myURL]]; 

// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

//Print contents of json-string
NSArray *statuses = [parser objectWithString:json_string error:nil];
NSLog(@"Array Contents: %@", [statuses valueForKey:@"messages"]);
NSLog(@"Array Count: %d", [statuses count]);


NSDictionary *results = [json_string JSONValue];
NSArray *tweets = [[results objectForKey:@"messages"] objectForKey:@"message"];

for (NSDictionary *tweet in tweets)
{
    NSString *url = [tweet objectForKey:@"url"];
    NSLog(@"url is: %@",url);
}

I can pull out "messages" and see all of the "message" blocks, but I am unable to parse deeper and pull out the "user", "pass", and "url".

1
  • The json string is malformed, the way you have written it here. The messages array has two open curly braces, and only one closing. Commented Mar 10, 2010 at 9:05

3 Answers 3

9

Solved:

NSArray *tweets = [[results objectForKey:@"messages"] valueForKey:@"message"];
Sign up to request clarification or add additional context in comments.

1 Comment

Can you explain this answer a little bit more?
6
Array({

  0=>Dictionary({

      response =  Array({

        0=>Dictionary(Status = 200)

      })

    }),

  1=>Dictionary({

      messages = Array({

        0=> Dictionary({

          message = Array({

            0=>Dictionary({

              user = value,

              pass=value,

                 url=value

            })

          })

        })

      })

  })

})

So, to access dictionary for user, pass, url,

nsarray *arr = jsonmainarray;


arr = [[[jsonmainarray objectAtIndex: 1] objectforkey:@"messages"] objectatindex: 0];



nsdictionary *dict = [arr objectatindex: 0];

arr = [dict objectforkey:@"message"];

dict = [arr objectatindex: 0]; // Dictionary with user, pass, url

Comments

2

there is an easier way (in my opinion) to do JSON parsing :)

- (void)loadJSONData:(NSString *)u{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://expandurl.appspot.com/expand?url=%@", u]];
    NSData *rawJsonData = [NSData dataWithContentsOfURL:url];

    CJSONDeserializer *parser = [CJSONDeserializer new];
    NSError *error;
    NSDictionary *jsonDictionary = [parser deserializeAsDictionary:rawJsonData error:&error];

    [parser release];

    NSArray *array = [jsonDictionary objectForKey:@"urls"]; 
}

All you have to do is to use JSON touch... like Sheehan Alam mention.

Say that you got this line of JSON data:

{ "end_url" = "http://www.youtube.com"; redirects = 0; "start_url" = "http://www.youtube.com"; status = OK; urls = ( "http://www.youtube.com" ); }

then in your JSONDictonary the data can be accessed by doing:

[jsonDictionary objectForKey:@"urls"]; //This will return an Array since URLS is a array
[jsondictionary objectForKey:@"en_url"]; //this will return an NSString since end_url is a string

Hope this help people as much as it helped me =)

sincerely yours Kristian

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.