-3

So this is my code to get a post json array from a url

// SENDING A POST JSON
    NSString *post = [NSString stringWithFormat:@"plm=1"];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:[NSURL URLWithString:@"http://muvieplus.com/testjson/test.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];


    NSURLResponse *requestResponse;
    NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];

    NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
    NSLog(@"%@", requestReply);

When i run it i got the requestReply

2014-11-07 14:22:15.565 JsonApp[1849:60b] 
{
    {"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

How can i parse this json ? Any help please ?

Kampai
  • 22,848
  • 21
  • 95
  • 95
Alex Bonta
  • 101
  • 4
  • 15
  • possible duplicate of [JSON Parsing in iOS 7](http://stackoverflow.com/questions/19404327/json-parsing-in-ios-7) – dandan78 Nov 07 '14 at 12:58
  • I would suggest a JSON parser, like NSJSONSerialization, which you would have found if you'd made the slightest attempt to search before asking your question. – Hot Licks Nov 07 '14 at 13:04
  • possible duplicate of [JSON parser for Cocoa](http://stackoverflow.com/questions/9454108/json-parser-for-cocoa) – Hot Licks Nov 07 '14 at 13:06

1 Answers1

2

Use the NSJSONSerialization class to get an object from JSON data.

NSError *error;
NSDictionary *requestReply = [NSJSONSerialization JSONObjectWithData:[requestHandler bytes] options:NSJSONReadingAllowFragments error:&error]
if (requestReply) {
    //use the dictionary
}
else {
    NSLog("Error parsing JSON: %@", error);
}

This will return a dictionary (depending on the data, it could be an array) containing all the objects in the JSON, which you can then use to build an object of your own or whatever.

I would suggest investigating the use of asynchronous requests, probably using NSURLSession or a third party library like AFNetworking, as this will make your app more responsive. You shouldn't even load a local file using the synchronous APIs, let alone make a network request, as your app won't be able to do anything else (on the current thread) until it gets a response, which could be a very long time, particularly when people are using cellular data.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
Josh Heald
  • 3,907
  • 28
  • 37