在iOS中创建一个JsonString

时间:2012-08-09 11:44:38

标签: iphone objective-c ios xcode

我是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这个json String使用RESTful Web Service到外部数据库。 考虑到我的主要目标,基本上哪种方式更好?

5 个答案:

答案 0 :(得分:9)

你应该使用NSJSONSerialization,因为它更快,直接使用iOS SDK,只要你的“目标受众”是iOS5 +

要将数据发布到您的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协议。

答案 1 :(得分: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);

For< iOS 5

使用json-framework使用NSDictionary类别提供json字符串的第三方库:

 NSString *jsonString = [dictionary JSONRepresentation];

 //with options
 NSString *jsonString = [dictionary JSONStringWithOptions:JKSerializeOptionNone error:nil]

答案 2 :(得分:1)

这将有助于您...... Convert NSDictionary to JSON with SBJson

答案 3 :(得分: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);

答案 4 :(得分: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; 
}