How to convert XML string to JSON using iPhone sdk

前端 未结 2 1996
臣服心动
臣服心动 2020-12-29 16:39

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. Ca

相关标签:
2条回答
  • 2020-12-29 17:11

    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/

    0 讨论(0)
  • 2020-12-29 17:12

    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);
    
    0 讨论(0)
提交回复
热议问题