IOS开发之----NSDictionary,JSON和XML互相转换

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IOS开发之----NSDictionary,JSON和XML互相转换相关的知识,希望对你有一定的参考价值。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self test];
    // Override point for customization after application launch.
    return YES;
}
 
-(void)test {
    
    //XML文本范例
    NSString *testXMLString = @"Cake0.55RegularChocolateBlueberryNoneGlazedSugar";
    
    NSLog(@"xml string[\n%@\n]", testXMLString);
    // 解析XML为NSDictionary
    NSError *parseError = nil;
    NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
    // 打印 NSDictionary
    NSLog(@"%@", xmlDictionary);
    
    //NSDictionary转换为Data
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:xmlDictionary options:NSJSONWritingPrettyPrinted error:&parseError];
    
    //Data转换为JSON
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSLog(@"jsonData string[\n%@\n]", str);
    //字符组转换为NSDictionary
    NSDictionary *jsonDict = [str objectFromJSONString];
    
    //NSDictionary转换为XML的plist格式
    NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:jsonDict
                                                                 format:NSPropertyListXMLFormat_v1_0
                                                       errorDescription:NULL];
    
    //Data转换为NSString输出 编码为UTF-8
    NSLog(@"XML: %@", [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding]);
    
    
   
    NSLog(@"%@",[XMLWriter XMLStringFromDictionary:jsonDict withHeader:NO]);
 
}

以上是关于IOS开发之----NSDictionary,JSON和XML互相转换的主要内容,如果未能解决你的问题,请参考以下文章

iOS之NSDictionary初始化的坑

NSDictionary实现原理-ios哈希hash和isEqual

iOS 开发,NSDictionary 和 Model 哪个好

IOS开发-ObjC-NSDictionary

iOS开发之 app网络实时监测

iOS开发之Appstore篇——版本更新