zoukankan      html  css  js  c++  java
  • 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[ %@ ]", testXMLString);
        // 解析XML为NSDictionary
        NSError *parseError = nil;
        NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
        // 打印 NSDictionary
        NSLog(@"%@", xmlDictionary);
        
        //NSDictionary转换为Data
        NSData* jsonData = [NSJSONSerialization dataWithJSONObject:xmlDictionaryoptions:NSJSONWritingPrettyPrinted error:&parseError];
        
        //Data转换为JSON
        NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        NSLog(@"jsonData string[ %@ ]", 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]);
     
    }
     
    //其中用到了三个类库,分别为
    1,JSONKit       https://github.com/johnezang/JSONKit
     
     
     
    下面连接是XML转换为Dictionary
    https://github.com/nicklockwood/XMLDictionary
    http://download.csdn.net/detail/p709723778/6706331
  • 相关阅读:
    Mysql 批量插入数据的方法
    sql server 多行合并一行
    跨服务器多库多表查询
    OPENQUERY用法以及使用需要注意的地方
    C# 判断操作系统的位数
    rpc介绍
    JavaScript decodeURI()与decodeURIComponent() 使用与区别
    UNIX 时间戳 C#
    C# winform javascript 互调用
    oracle 实例名和服务名以及数据库名区别
  • 原文地址:https://www.cnblogs.com/Milo-CTO/p/4224884.html
Copyright © 2011-2022 走看看