XML转换为iOS中的JSON转换

我需要将XML响应转换为JSON并将其转换为json To javaScript代码。

My XML response:  True 02291c402-2220-422b-b199-f92f22e56d2f  

我正在使用来自此站点的XMLReader支持文件:

XMLReader的

我使用此代码将XML转换为JSON:

 + (NSString*) XMLToJson:(CXMLDocument *)xmlDocument { NSError *error = nil; NSArray *resultNodes = [xmlDocument nodesForXPath:@"//cell" error:&error]; if(error) NSLog(@"%@",error.description); CXMLNode *cellNode = [resultNodes objectAtIndex:0]; NSLog(@"%@",cellNode.XMLString); NSError *parseError = nil; NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:cellNode.XMLString error:&parseError]; NSLog(@"%@", xmlDictionary); //{print this. // cell = { // Result = { // text = True; // }; // sguid = { // text = "0391c402-1120-460b-b199-f92fffe56d2f"; // }; // }; //} NSData *jsonData = [NSJSONSerialization dataWithJSONObject:xmlDictionary options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string error:&error]; if(error) NSLog(@"%@",error.description); NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"%@", jsonString); return jsonString; } 

我得到了像这样的JSON响应:

 { "cell" : { "Result" : { "text" : "True" }, "sguid" : { "text" : "0391c402-1120-460b-b199-f92fffe56d2f" } } } 

我需要像这样的JSON响应:

 { "cell": { "Result": "True", "sguid": "02291c402-2220-422b-b199-f92f22e56d2f" } } 

因为然后我发送这个json到javascript代码我得到了exceptionjquery mobile不知道解析器这个并抛出语法错误的exception。

我见过程序员使用这个解决方案并帮助他们,但我仍然在这个解决方案中获得相同的结果。

XML转换为iOS中的JSON转换

谢谢

我刚刚为你的问题编写了一个函数,我尝试了几个XML。 如果您发现任何问题,请告诉我

 - (NSMutableDictionary *)extractXML:(NSMutableDictionary *)XMLDictionary { for (NSString *key in [XMLDictionary allKeys]) { // get the current object for this key id object = [XMLDictionary objectForKey:key]; if ([object isKindOfClass:[NSDictionary class]]) { if ([[object allKeys] count] == 1 && [[[object allKeys] objectAtIndex:0] isEqualToString:@"text"] && ![[object objectForKey:@"text"] isKindOfClass:[NSDictionary class]]) { // this means the object has the key "text" and has no node // or array (for multiple values) attached to it. [XMLDictionary setObject:[object objectForKey:@"text"] forKey:key]; } else { // go deeper [self extractXML:object]; } } else if ([object isKindOfClass:[NSArray class]]) { // this is an array of dictionaries, iterate for (id inArrayObject in (NSArray *)object) { if ([inArrayObject isKindOfClass:[NSDictionary class]]) { // if this is a dictionary, go deeper [self extractXML:inArrayObject]; } } } } return XMLDictionary; } 

并像这样使用它

 NSDictionary *clearXML = [[self extractXML:[yourParsedXMLDictionary mutableCopy]] copy]; 

您在使用XMLReader时遇到的问题。 要解决此问题,您可以使用XMLConverter而不是XMLReader。