Chhewang
Chhewang

Reputation: 9

How to read Java generated JSON data from Objective C?

I have generated JSON data from Java Restful WebServices and I need to put into the Objective C code. How can I use the JSON data and integrate into Objective C? The IDE has generated the local URL, how can I use the generated JSON data in other machine. Thank you

Upvotes: 1

Views: 347

Answers (3)

Rob
Rob

Reputation: 437872

You can request the NSData from the URL and then use NSJSONSerialization to interpret it. For example:

NSURL *url = [NSURL URLWithString:@"http://www.put.your.url.here/test.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {
        NSLog(@"%s: sendAsynchronousRequest error: %@", __FUNCTION__, error);
        return;
    }

    NSError *jsonError = nil;
    NSArray *results = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"%s: JSONObjectWithData error: %@", __FUNCTION__, jsonError);
        return;
    }

    // now you can use the array/dictionary you got from JSONObjectWithData; I'll just log it

    NSLog(@"results = %@", results);
}];

Clearly, that assumed that the JSON represented an array. If it was a dictionary, you'd replace the NSArray reference with a NSDictionary reference. But hopefully this illustrates the idea.

Upvotes: 1

Paul Dardeau
Paul Dardeau

Reputation: 2619

Have a look at NSURLConnection to retrieve the JSON from your web service. Then you can make use of NSJSONSerialization to parse it.

Upvotes: 1

Nuoji
Nuoji

Reputation: 3448

Use any of the many JSON parsers available. This question compares a few of them: Comparison of JSON Parser for Objective-C (JSON Framework, YAJL, TouchJSON, etc)

Upvotes: 1

Related Questions