Question

Following this example of JSONModel

#import "CountryModel.h"
...

NSString* json = (fetch here JSON from Internet) ... 
NSError* err = nil;
CountryModel* country = [[CountryModel alloc] initWithString:json error:&err];

I mimic it this way

// Here is the class #import "JSONModel.h"

@interface OrderNumberModel : JSONModel
@property (strong, nonatomic) NSString* OrderNumber;
@property (strong, nonatomic) NSString* OrderDate;

@end


NSString* json = (fetch here JSON from Internet) ... 

NSError* err = nil;
OrderNumberModel *order = [[OrderNumberModel alloc] initWithString:result error:&err];

NSLog(@"Order Number: %@ Order Date: %@", order.OrderNumber, order.OrderDate);

if the class init method is initWithString how can I fetch json as string? most of the examples I have seen does is as NSData. the url of my local server method return a new orderNumber and the current date. NSURL *url = [NSURL URLWithString:@"http://myserver/service/api/punumber/"] returns =>["13025","11/12/2013 2:26:24 PM"] Thanks.

Was it helpful?

Solution

Your server does not return an object (rather a list of strings) - therefore you can't parse the response with a model class.

In case the server returned for example:

{"OrderNumber":"13025", "OrderDate":"11/12/2013 2:26:24 PM"}

THEN you could use your model class to parse this, because JSONModel can match the JSON key names to your class property names:

@interface OrderNumberModel : JSONModel
@property (strong, nonatomic) NSString* OrderNumber;
@property (strong, nonatomic) NSString* OrderDate;
@end

BUT since your server just returns two strings, without keys you can't have them automatically mapped to a model class.

What you CAN do though is to use JSONModel's built in HTTP client.

#import "JSONModel+networking.h"

[JSONHTTPClient getJSONFromURLWithString:@"your URL as string"
    completion:^(id json, JSONModelError *err) {
        NSArray* array = (NSArray*)json;
        NSString* orderNr = array[0];
        NSString* orderDate = array[1];
}];

OTHER TIPS

I use to do this with NSURLRequest, you need to call it as something like:

theURL = [[NSURL URLWithString:@"http://myserver.com/json/method"] retain]; 
NSURLRequest *request = [NSURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

And then implement the delegate methods in your controller and the important stuff goes here:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSString *content = [[[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding] autorelease];
    /*...*/
}

Where *content is a JSON NSString.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top