在iOS中创建一个JsonString [英] Create a JsonString in iOS

查看:155
本文介绍了在iOS中创建一个JsonString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iOS新手。我创建了一个 JSON NSDictionary ,如下所示:

I am new in iOS. I created a JSON NSDictionary like this:

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

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

And then I could convert it to NSString via two mechanisms:

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

第二种方式我得到这个警告

In the second way I get this 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?

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

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

推荐答案

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

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

将数据发布到您需要在这些行上创建请求的Web服务...

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

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 协议。

这篇关于在iOS中创建一个JsonString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆