0

If I have a json string as below, what's the best way to get the first iteration of the name (bob) in objective-c?

{
    "users": [
        {"id": "1", "name": "bob"},
        {"id": "2", "name": "john"},
        {"id": "3", "name": "joe"}
    ]
}

BTW, I'm currently using JSONKit to parse the json string. For example, NSDictionary *users = [jsonString objectFromJSONString];

3
  • 1
    That JSON isn't valid. JSON can only have a single outer object. Should it be wrapped in []? Commented Aug 21, 2013 at 14:43
  • 2
    I would suggest you consider Apple's NSJSONSerialization which has existed since iOS 5. One less dependency. Commented Aug 21, 2013 at 14:48
  • This is blazingly simple: You have an "object" (dictionary) containing one element named "users". That one element is an array. The array elements are objects/dictionaries containing two elements. What have you tried?? Commented Aug 21, 2013 at 15:12

2 Answers 2

1

Your "users" container is a NSDictionary, and this is an unordered associative container.

That is, strictly, there is no "first" element (a user). Of course, you can iterate with fast enumeration and get a first user, however which one is "implementation defined" (and since the implementation is not public, we do not know which one).

Edit:

Since now, after your edit, your "users" container is an array, the things change dramatically ;) Someone else give an answer.

Sign up to request clarification or add additional context in comments.

Comments

0

OK, first thing to do is drop any third party frameworks for JSON. There is now a native JSON class...

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding: NSUTF8StringEncoding] options:0 error:nil];

NSArray *users = dictionary[@"users"];

Once you've done this you can iterate the users array like you would any other array.

Each object in the users array is an NSDictionary with keys @[@"id", @"name"]

e.g.

for (NSDictionary *userDict in users) {
    NSLog(@"User name = %@", userDict[@"name"]);
}

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.