xcode 在 iOS 中创建一个 JsonString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11882696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 01:11:37  来源:igfitidea点击:

Create a JsonString in iOS

iphoneobjective-ciosxcode

提问by Ali

I am new in iOS. I created a JSON NSDictionarylike this:

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

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

And then I could convert it to NSStringvia two mechanisms:

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

1)

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)

2)

NSString *jsonString = [jsonDictionary JSONRepresentation];

In the second way I get this warning:

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

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

But when I run the project, both of the mechanisms works fine:

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

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

Do you know how can I remove the warning in the second way?

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

My main goal is POSTthis json String to an external database using RESTful Web Service. Basically which way is better considering my main goal?

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

回答by Peter Pajchl

You should use NSJSONSerializationas it is faster and comes directly with iOS SDK as long as your "target audience" is iOS5+

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

To POST the data to your web service you need the create a request along these lines...

要将数据发布到您的 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];

Please read up on NSURLConnectionDelegateprotocol.

请阅读NSURLConnectionDelegate协议。

回答by Paresh Navadiya

For iOS 5.0 >:

对于 iOS 5.0 >

Use NSJSONSerializationlike this :

像这样使用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:

对于 < iOS 5

Use json-frameworka third party library that uses category for NSDictionaryto provide json string :

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

 NSString *jsonString = [dictionary JSONRepresentation];

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

回答by alloc_iNit

回答by Senthilkumar

use this way i hope it will help you

使用这种方式我希望它会帮助你

 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);

回答by Arjun

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; 
}