Sekhar Bhetalam
Sekhar Bhetalam

Reputation: 4535

How to convert XML string to JSON using iPhone sdk

I am implementing a client based application. In that I have an xml string. I need to convert it to JSON format and send to the server. I have no idea on converting this. Can you guys please suggest me any documentation or idea to this?

Upvotes: 4

Views: 9262

Answers (2)

As Steve said the two steps are those, I leave you a bit of code, maybe can help you a bit more:

// Don't forget the imports ;)
#import "XMLReader.h"

// You must have a XML string from somewhere
NSString XMLString = yourXML;
// I remove all returns and tabs from the text, after i would be annoying if you don't remove it
XMLString = [XMLString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
XMLString = [XMLString stringByReplacingOccurrencesOfString:@"\t" withString:@""];

// Parse the XML into a dictionary
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:XMLString error:&parseError];

NSError *error;
self.dataParsed = [NSJSONSerialization dataWithJSONObject:xmlDictionary
                                                   options: NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                     error:&error];

// Print the dictionary
NSLog(@"%@", xmlDictionary);

Upvotes: 0

Steve
Steve

Reputation: 31642

Step #1: Read XML into NSDictionary: http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/

Step #2: Convert NSDictionary into JSON: http://code.google.com/p/json-framework/

Upvotes: 11

Related Questions