1

我是 iOS 新手。我创建了一个JSON NSDictionary这样的:

NSArray *keys = [NSArray arrayWithObjects:@"User", @"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:@"Ali", @"2020", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

然后我可以NSString通过两种机制将其转换为:

1)

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];

NSString *jsonString = nil;
if (! jsonData) {
     NSLog(@"Got an error: %@", error);
} else {
     jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

2)

NSString *jsonString = [jsonDictionary JSONRepresentation];

在第二种方式中,我得到了这个warning

Instance method '-JSONRepresentation' not found (return type defaults to 'id')

但是当我运行该项目时,两种机制都可以正常工作:

NSLog(@"Val of json parse obj is %@",jsonString); 

您知道如何以第二种方式删除警告吗?

我的主要目标是POST使用 RESTful Web 服务将此 json 字符串传输到外部数据库。基本上考虑到我的主要目标,哪种方式更好?

4

5 回答 5

9

NSJSONSerialization只要您的“目标受众”是 iOS5+,您就应该使用它,因为它更快并且直接与 iOS SDK 一起提供

要将数据发布到您的 Web 服务,您需要按照以下方式创建请求...

NSDictionary * postDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"value1", @"value2", nil]
                                                                  forKeys:[NSArray arrayWithObjects:@"key1", @"key2", nil]];

NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONReadingMutableContainers error:&error];

NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"your_webservice_post_url"]];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:jsonData];

NSURLConnection * myConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];

请阅读NSURLConnectionDelegate 协议。

于 2012-08-09T12:44:39.063 回答
4

对于 iOS 5.0 >

像这样使用NSJSONSerialization

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *resultAsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
 NSLog(@"jsonData as string:\n%@ Error:%@", resultAsString,error);

对于 < iOS 5

使用json-framework第三方库,它使用 categoryNSDictionary来提供 json 字符串:

 NSString *jsonString = [dictionary JSONRepresentation];

 //with options
 NSString *jsonString = [dictionary JSONStringWithOptions:JKSerializeOptionNone error:nil]
于 2012-08-09T11:59:34.433 回答
1

这将帮助您...使用 SBJson 将 NSDictionary 转换为 JSON

于 2012-08-09T11:47:19.970 回答
0

用这种方式希望对你有帮助

 NSArray *keys = [NSArray arrayWithObjects:@"User", @"Password", nil];
 NSArray *objects = [NSArray arrayWithObjects:@"Ali", @"2020", nil];
 NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

 NSError *error = nil;
 // NSError *error; 
 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];


 id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

 NSLog(@"\n\n\n id for json==%@ \n\n\n\n\n",result);
于 2012-08-09T11:59:35.777 回答
0
JSON DEFAULT METHOD......

+(NSDictionary *)stringWithUrl:(NSURL *)url postData:(NSData *)postData httpMethod:(NSString *)method { 

NSDictionary *returnResponse=[[NSDictionary alloc]init];

@try {
 NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:180]; [urlRequest setHTTPMethod:method];

if(postData != nil)
{
    [urlRequest setHTTPBody:postData];
}

[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"text/html" forHTTPHeaderField:@"Accept"];

NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                returningResponse:&response
                                            error:&error];
returnResponse = [NSJSONSerialization
                  JSONObjectWithData:urlData
                  options:kNilOptions
                  error:&error];
} @catch (NSException *exception) { returnResponse=nil; } @finally { return returnResponse; } }

Return Method :

+(NSDictionary )methodName:(NSString)string { 
NSDictionary *returnResponse; NSData *postData = [NSData dataWithBytes:[string UTF8String] length:[string length]]; NSString *urlString = @"https//:..url...."; returnResponse=[self stringWithUrl:[NSURL URLWithString:urlString] postData:postData httpMethod:@"POST"];
return returnResponse; 
}
于 2015-11-26T17:07:44.453 回答