1

如何在IOS6的JSON解析中获取和插入数据

我正在尝试使用 JSONParser 将数据插入 JSON 链接并从 JSON 链接检索数据。

如何在 IOS6 中不添加 JSON 框架的情况下使用 JSON Parser。

4

3 回答 3

2

“不添加 JSON 框架”是什么意思?是不是说要自己解析JSON?当有好的图书馆存在时,你为什么要重新发明轮子?

我推荐JSONKit,一个快速且编写良好的 Objective-C 库。您只需在项目中包含两个文件,您就可以从 JSON 中解析和序列化数据。

如果您想学习 JSON 并想创建自己的库以用于学习目的,请首先阅读本文以了解 JSON 是什么以及它的语法是什么。从这里您可以考虑如何将字典实现为 JSON(甚至对象为 JSON)。

于 2013-04-15T18:38:02.833 回答
1

首先你需要导入 JSON 文件,你会从这里得到

然后,如果您使用的是 POST 方法,请执行以下操作:

NSString *myRequestString = [NSString stringWithFormat:@"u=%@&p= %@",strUname,strPassword];
myRequestString=[myRequestString stringByReplacingOccurrencesOfString:@" " withString:@""];
NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[myRequestString length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: @"Your Webservice URL"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:myRequestData];

NSData *returnData = nil;
returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
NSDictionary *myDic = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];

如果您使用的是 GET 方法,请使用以下方法:

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"Your WebService with Parameters in URL"]]];
NSDictionary *MyDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

希望这会有所帮助。

于 2013-04-17T05:34:41.397 回答
1
NSString *Post=[NSString stringWithFormat:@"email=%@&username=%@&password=%@",,Text_Email.text,Text_User.text,Text_Password.text];
NSData *PostData = [Post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *PostLengh=[NSString stringWithFormat:@"%d",[Post length]];
NSURL *Url=[NSURL URLWithString:[NSString stringWithFormat:@"%@usersignup.php",ServerPath]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:Url     cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
[request setHTTPMethod:@"POST"];
[request setValue:PostLengh forHTTPHeaderField:@"Content-Lenght"];
[request setHTTPBody:PostData];

NSData *ReturnData =[NSURLConnection sendSynchronousRequest:request returningResponse:Nil error:Nil];     
NSString *Response = [[NSString alloc] initWithData:ReturnData encoding:NSUTF8StringEncoding];     
Response = [Response stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
于 2013-08-16T09:43:31.670 回答