objective-c如何在 ios 解析成 Json 格式的数据?

发布时间: 2016/10/4 1:19:28
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我已转换 NSData,然后我得到字符串的字符串像下面,现在我想解析这一。如果解析 json serilazation 与我得到的 json 数据为零。

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><EmployeesLoginMethodResponse xmlns="http://tempuri.org/"><EmployeesLoginMethodResult>[{"sms":"You have logged in successfully!","userId":"29","type":"1","name":"mng 56 78"}]</EmployeesLoginMethodResult></EmployeesLoginMethodResponse></soap:Body></soap:Envelope>

如果我将解析使用XML我得到字符串在这下面,喜欢如何获取值的短信用户 Id名称

 [{
  "sms": "You have logged in successfully!",
  "userId": "13",
  "type": "1",
  "name": "Suhashini Kumari Singh"
 }]

这里是我的代码

   NSString *urlString=[NSString stringWithFormat:@"http://workforce.wifisocial.in/WebServicesMethods/EmployeesWebService.asmx"];
NSString* webStringURL = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString* requestBody =[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><EmployeesLoginMethod xmlns=\"http://tempuri.org/\"><username>\%@</username><password>\%@</password><IpAddress>\%@</IpAddress><deviceName>\%@</deviceName></EmployeesLoginMethod></soap:Body></soap:Envelope>",self.userNameTextFiled.text,self.passwordTextField.text,ipAddress,deviceName];

[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"text/xml" forHTTPHeaderField:@"Content-type"];

[request setValue:@"\"http://tempuri.org/EmployeesLoginMethod\"" forHTTPHeaderField:@"SOAPAction"];

[request setHTTPBody:[requestBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]] ;

NSError *error;
NSHTTPURLResponse *response = nil;
NSData * urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Response code: %ld", (long)[response statusCode]);

NSString* responseString = [NSString stringWithUTF8String:[urlData bytes]];
   NSLog(@"%@",responseString);
if (urlData)
{
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];

解决方法 1:

如果你有你的反应在 json 字符串然后试试像下面,

 NSError *jsonError;
 NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                  options:NSJSONReadingMutableContainers 
                                    error:&jsonError];

这里 responseString 是您发布问题的最终输出 json 字符串。

然后获取数据从 json dictionary

如果这种情况下将不起作用,然后看看NSXMLParser,你可以参考Appcoda 的教程

官方微信
官方QQ群
31647020