如何在ios中将数据解析为Json格式?

时间:2016-09-02 11:15:43

标签: ios objective-c json soap

我将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 解析我正在获取字符串,如下所示,在此如何获取短信的值, userId 下,的名称

 [{
  "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];

4 个答案:

答案 0 :(得分:4)

请尝试使用XMLDictionary库。有关更多参考https://github.com/nicklockwood/XMLDictionary

只需使用XMLDictionary将NSData转换为NSDictionary,如下所示

NSDictionary *xmlDictionary = [NSDictionary dictionaryWithXMLData:returnData];

答案 1 :(得分:2)

如果你在json字符串中得到了回复,那么请尝试如下,

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

此处responseString是您发布的最终输出json字符串。

然后从json dictionary获取数据。

如果此方案无效,请查看NSXMLParser,您可以参考Appcoda's tutorial

答案 2 :(得分:0)

您可以使用XML到JSON转换器(XMLReader) :https://github.com/amarcadet/XMLReader

#import "XMLReader.h"

以下是代码的示例代码段:

NSData * urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (urlData)
    {
        NSDictionary *dict = [XMLReader dictionaryForXMLData:urlData error:&error];
              NSLog(@"-----%@-----",dict);
NSError *jsonError;
        NSString *json2 = [[[[[[dict valueForKey:@"soap:Envelope"] valueForKey:@"soap:Body"] valueForKey:@"EmployeesLoginMethodResponse"] valueForKey:@"EmployeesLoginMethodResult"] valueForKey:@"text"] stringByReplacingOccurrencesOfString:@"\"" withString:@"\""];

        NSData *objectData1 = [json2 dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *json1 = [NSJSONSerialization JSONObjectWithData:objectData1 options:NSJSONReadingMutableContainers error:&jsonError];

        NSLog(@"-----%@-----",json1);
    }

答案 3 :(得分:0)

它是nil,因为它不是失败的JSON解析,而是因为结果对象的条件类型转换为字典。

这是一个包含一个词典的数组。因此,在解析过程中将其转换为NSArray

像,

而不是:

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];

使用:

NSArray *arrJson=[NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];

NSDictionary *json = [arrJson objectAtIndex:0];

NSString *sms=[json valueForKey:@"sms"];
NSString *userId=[json valueForKey:@"userId"];
NSString *type=[json valueForKey:@"type"];
NSString *name=[json valueForKey:@"name"];