遵循JSONModel的这个例子
#import "CountryModel.h"
...
NSString* json = (fetch here JSON from Internet) ...
NSError* err = nil;
CountryModel* country = [[CountryModel alloc] initWithString:json error:&err];
我这样模仿
//这是班级 #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);
如果类init方法是initWithString,我如何将json作为字符串获取?我见过的大多数例子都是NSData。我的本地服务器方法的url返回一个新的orderNumber和当前日期。 NSURL *url = [NSURL URLWithString:@"http://myserver/service/api/punumber/"]
返回=> [" 13025"," 11/12/2013 2:26:24 PM"]谢谢。
答案 0 :(得分:0)
我用NSURLRequest
执行此操作,您需要将其称为:
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];
然后在控制器中实现委托方法,重要的事情就在这里:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *content = [[[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding] autorelease];
/*...*/
}
*content
是JSON NSString。
答案 1 :(得分:0)
您的服务器不返回对象(而是字符串列表) - 因此您无法使用模型类解析响应。
如果服务器返回例如:
{"OrderNumber":"13025", "OrderDate":"11/12/2013 2:26:24 PM"}
那么您可以使用模型类来解析它,因为JSONModel可以将JSON键名与您的类属性名匹配:
@interface OrderNumberModel : JSONModel
@property (strong, nonatomic) NSString* OrderNumber;
@property (strong, nonatomic) NSString* OrderDate;
@end
但是,因为你的服务器只返回两个字符串,没有键,你就不能将它们自动映射到一个模型类。
你可以做的是使用JSONModel的内置HTTP客户端。
#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];
}];