13

I'm newbie in iOS dev and I'm trying to parse a local Json file such as

{"quizz":[{"id":"1","Q1":"When Mickey was born","R1":"1920","R2":"1965","R3":"1923","R4","1234","response","1920"},{"id":"1","Q1":"When start the cold war","R1":"1920","R2":"1965","R3":"1923","rep4","1234","reponse","1920"}]}

here is my code:

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
// Parse the string into JSON
NSDictionary *json = [myJSON JSONValue];

// Get all object
NSArray *items = [json valueForKeyPath:@"quizz"];

NSEnumerator *enumerator = [items objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
    NSLog(@"clientId = %@",  [item objectForKey:@"id"]);
    NSLog(@"clientName = %@",[item objectForKey:@"Q1"]);
    NSLog(@"job = %@",       [item objectForKey:@"Q2"]);
}

I found on this site a sample but I get the following error

-JSONValue failed. Error is: Token 'value separator' not expected after object key.

0

5 Answers 5

14

JSON has a strict key/Value notation, your key/value pairs for R4 and response are not correct. Try this:

NSString *jsonString = @"{\"quizz\":[{\"id\":\"1\",\"Q1\":\"When Mickey was born\",\"R1\":\"1920\",\"R2\":\"1965\",\"R3\":\"1923\",\"R4\":\"1234\",\"response\":\"1920\"}]}";

If you read the string from a file, you don't need all the slashes
Your file would be something like this:

{"quizz":[{"id":"1","Q1":"When Mickey was born","R1":"1920","R2":"1965","R3":"1923","R4":"1234","response":"1920"},{"id":"1","Q1":"When start the cold war","R1":"1920","R2":"1965","R3":"1923","R4":"1234","reponse":"1920"}]}


I tested with this code:

NSString *jsonString = @"{\"quizz\":[{\"id\":\"1\",\"Q1\":\"When Mickey was born\",\"R1\":\"1920\",\"R2\":\"1965\",\"R3\":\"1923\",\"R4\":\"1234\",\"response\":\"1920\"}, {\"id\":\"1\",\"Q1\":\"When start the cold war\",\"R1\":\"1920\",\"R2\":\"1965\",\"R3\":\"1923\",\"R4\":\"1234\",\"reponse\":\"1920\"}]}";
NSLog(@"%@", jsonString);
NSError *error =  nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];

NSArray *items = [json valueForKeyPath:@"quizz"];

NSEnumerator *enumerator = [items objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
    NSLog(@"clientId = %@",  [item objectForKey:@"id"]);
    NSLog(@"clientName = %@",[item objectForKey:@"Q1"]);
    NSLog(@"job = %@",       [item objectForKey:@"Q2"]);
}

I got the impression, that you copied old code, as you are not using apple's serialization and a Enumerator instead of Fast Enumeration. The whole enumeration stuff could be written simple as

NSArray *items = [json valueForKeyPath:@"quizz"];
for (NSDictionary *item in items) {
    NSLog(@"clientId = %@",  [item objectForKey:@"id"]);
    NSLog(@"clientName = %@",[item objectForKey:@"Q1"]);
    NSLog(@"job = %@",       [item objectForKey:@"Q2"]);
}

or even fancier with block based enumeration, hwere you have additionaly an index if needed to the fast and secure enumeration.

NSArray *items = [json valueForKeyPath:@"quizz"];
[items enumerateObjectsUsingBlock:^(NSDictionary *item , NSUInteger idx, BOOL *stop) {
    NSLog(@"clientId = %@",  [item objectForKey:@"id"]);
    NSLog(@"clientName = %@",[item objectForKey:@"Q1"]);
    NSLog(@"job = %@",       [item objectForKey:@"Q2"]);
}];
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much for your help. One other question, how I can retrieve a specific object index in the array and browse the key value? I mean if I want to select the second object directly and display the id value?
once you parsed the json string, you will have nsarrays and dictionaries. so for array you can do item = [items objectAtIndex:1] to get the second item. But this has nothing to do with json anymore. this is standard array/dictionary stuff.
4
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"json"];
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSError *error =  nil;
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:[myJSON dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];

Comments

2

Use jsonlint.com to find errors in your JSON string.
In this case, it says you have non-valid JSON near "R4"

Comments

0

There seems to be a typo in your json file.

Replace
"R4","1234","response","1920" with "R4":"1234","response":"1920"
and
"rep4","1234","reponse","1920" with "rep4":"1234","response":"1920"

Comments

0

Swift 2.3 I use a utility method to convert JSON files to a Dictionary:

func getDictionaryFromJSON(jsonFileName: String) -> [String: AnyObject]? {
    guard let filepath = NSBundle.mainBundle().pathForResource(jsonFileName, ofType: "json") else {
        return nil
    }

    guard let data = NSData(contentsOfFile: filepath) else {
        return nil
    }

    do {
        let dict = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject]
        return dict
    } catch {
        print(error)
        return nil
    }
}

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.