-2

Here is what I want to parse.

   {
        "Words": {
            "subjugate": "To conquer. ",
            "contemplate": "To consider thoughtfully. ",
            "comprise": "To consist of. ",
            "pollute": "To contaminate. "
        }
    }
ErstwhileIII
  • 4,829
  • 2
  • 23
  • 37
  • Are you using Swift or Objective C? – rocket101 Aug 23 '14 at 14:09
  • apple's native class works well:https://developer.apple.com/library/ios/documentation/foundation/reference/nsjsonserialization_class/Reference/Reference.html. I also like SBJson4: https://github.com/stig/json-framework/ – mitrenegade Aug 23 '14 at 14:10
  • possible duplicate of [iPhone/iOS JSON parsing tutorial](http://stackoverflow.com/questions/5813077/iphone-ios-json-parsing-tutorial) – rohan-patel Aug 23 '14 at 14:12

2 Answers2

1

Here is a very stripped and over-simplified way to handle getting response data back from a server in JSON and serializing the JSON to an NSDictionary:

    // this is just for example purposes, in this example the code is already running on a background thread so sending it synhcronously is OK, and I've already created the request object
    NSError *error = nil;  
    NSHTTPURLResponse *response = nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    // if we don't have response data
    if (!responseData) {
        // handle that we got no response from the server
    }

    if (error) {
       // handle the request error
    }

    // serialize the JSON result into a dictionary
    NSError *serializationError = nil;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 &serializationError];

    if (serializationError) {
       // handle the error turning the data into dictionary
    }

    NSDictionary *wordsDictionary = resultDictionary[@"words"];
    NSString *exampleValue = wordsDictionary[@"subjugate"]; // will be "To conquer." if everything goes to plan
Mike
  • 9,765
  • 5
  • 34
  • 59
0

You can parse as bellow

NSData *data = [@"{\"Words\":{\"subjugate\":\"To conquer.\",\"contemplate\":\"To consider thoughtfully.\",\"comprise\":\"To consist of.\",\"pollute\":\"To contaminate.\"}}" dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

if(error)
{
    NSLog(@"Error : %@", error);
}
else
{
    NSLog(@"%@", json);
}
Rajesh
  • 948
  • 7
  • 13