如何使用iPhone SDK将XML字符串转换为JSON

4

我正在实现一个基于客户端的应用程序。其中有一个XML字符串,我需要将其转换为JSON格式并发送到服务器。我不知道如何进行转换。请问你们能否向我提供任何文档或想法?

2个回答

11

0
如Steve所说,这两个步骤就是这些,我给您留下一点代码,或许可以再帮您一点忙:
// 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);

另外,我对XMLReader文件进行了一些修改,使其更符合我的需求。 - Mario Bañares Colastra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接