1

I am trying to parse JSON without keys. It looks like this one:

{
    "somestring": [
        "otherstring1",
        float],
    "somestring2": [
        "somestring3",
        float],
    "full":integer
}

How I am suppose to parse the first value for each object?

0

1 Answer 1

2

So, when you parse that, you will have a NSDictionary with for which the first two keys have a value which is an NSArray:

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error)
    NSLog(@"JSONObjectWithData error: %@", error);

NSArray *array = dictionary[@"22398f2"];
NSString *firstArrayItem = array[0];   // @"CBW32"
NSString *secondArrayItem = array[1];  // @50.1083

Or, if you want all of the first items, you could do something like:

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error)
    NSLog(@"JSONObjectWithData error: %@", error);

[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    NSArray *array = obj;
    if ([obj isKindOfClass:[NSArray class]])
        NSLog(@"first item = %@", array[0]);
    else
        NSLog(@"The value associated with key '%@' is not array", key);
}];
Sign up to request clarification or add additional context in comments.

3 Comments

@user776720 Your JSON does not appear to be an array. Your snippet excluded the { and } that should wrap what you presented, but we can infer this from the presence of the colon in what you did share with us (your JSON is missing a quotation mark, too). Anyway, this JSON snippet is a dictionary with two key-value pairs. The values are, themselves, NSArray. So, use NSJSONSerialization to get the dictionary, and then enumerate the keys and objects to get the arrays that are stored as the objects within that dictionary. And then grab the first item from each array. See expanded answer.
Hi Rob and thanks for your answer. It seems that is working but after some parsing it throws the erro:Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'obj should be array'

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.