How to convert XML string to JSON using iPhone sdk

别等时光非礼了梦想. 提交于 2020-01-10 09:21:18

问题


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?


回答1:


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/




回答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);


来源:https://stackoverflow.com/questions/6354159/how-to-convert-xml-string-to-json-using-iphone-sdk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!