JSON error: error <error: expected ']': 1 expression to parse errors>

I am having trouble parsing my JSON. JSON:

{"privatecode":"XDhUZQ1rA2gBZwshV2NrZQRnDmVPZQhuVj7WOlNrC29SPwg6VDUGelU1DahQNlc1AWpcPVBuWmc"}

I am using the following code:

id parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&localError];

The class parsedObjectis equal NSDictionary, but it contains the following error:

(<invalid>) [0] = <error: expected ']'
error: 1 errors parsing expression
>

Of course, I could say:

NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&localError];

but it does not matter. I just want to get privatecodeas an object NSString, so what I'm doing wrong and how can I fix it?

Thank you very much in advance.

EDIT: Another code I'm using:

NSLog(@"Response: %@", [request responseString]);
id parsedObject = [NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:&localError];

requesthas type ASIHTTPRequest. Log output:

Response: {"privatecode":"XDhUZQ1rA2gBZwshV2NrZQRnDmVPZQhuVj7WOlNrC29SPwg6VDUGelU1DahQNlc1AWpcPVBuWmc"}
+4
source share
2 answers

Use this:

NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&localError];

I use this for my project without any problems. Hope this helps. :)

EDIT:

, ( '['). JSON - ( '{'). . . :

if ([returnedFromWeb respondsToSelector:@selector(objectAtIndex:)]) { // you can replace respondsToSelector:@selector(objectAtIndex:) by isKindOfClass:[NSArray class]
  //it an array do array things.
} else {
  //it a dictionary do dictionary things.
}
+2

, , - . , , , .

    id test = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:error];
    NSArray *array;
    NSDictionary *dictionary;
    if ([test isKindOfClass:[NSArray class]]) { 
        //it an array do array things.
        array = [NSArray arrayWithArray:test];
    } else {
        //it a dictionary do dictionary things.
        dictionary = [NSDictionary dictionaryWithDictionary:test];
    }

.

:

NSArray *array = [NSArray arrayWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:error]];

NSDictionary *dictionary = [NSDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:error]];
0

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


All Articles