Dinesh Gurrapu
Dinesh Gurrapu

Reputation: 158

How to parse the data into Json Format in ios?

I Converted NSData to string then I am getting the string like below, Now I want to parse this one. If parse with json serilazation I am getting json data nil.

<?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>

If I parse using XML I am Getting The String Like below,In this How to get value of sms,userId,name

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

Here is my code

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

Upvotes: 2

Views: 1661

Answers (4)

Maulik Pandya
Maulik Pandya

Reputation: 2220

You can use XML to JSON converter (XMLReader) : https://github.com/amarcadet/XMLReader

#import "XMLReader.h"

Here is the sample snippet for your code :

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

Upvotes: 0

BSB
BSB

Reputation: 277

Please try XMLDictionary library. For more reference https://github.com/nicklockwood/XMLDictionary

Just convert your NSData to NSDictionary using XMLDictionary as below

NSDictionary *xmlDictionary = [NSDictionary dictionaryWithXMLData:returnData];

Upvotes: 4

Ketan Parmar
Ketan Parmar

Reputation: 27428

If you got you response in json string then try like below,

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

here responseString is final output json string that you have posted in question.

Then fetch data from json dictionary.

If this scenario will not work then take a look at NSXMLParser, you can refer Appcoda's tutorial.

Upvotes: 2

Ronak Chaniyara
Ronak Chaniyara

Reputation: 5435

It's nil because it's not the JSON parsing that's failing but because of the conditional type cast of the resulting object as a dictionary.

It's an array with one item which is dictionary. So, during parsing cast it as a NSArray.

Like,

Instead of:

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

Use:

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

Upvotes: 0

Related Questions