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

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOp tions:(NSDictionary *)launchOptions
{
      [self test];
      // Override point for customization after application launch.
      return YES;
}

-(void)test {
      
      //XML文本范例
      NSString *testXMLString = @"Cake0.55RegularChocolateBluebe rryNoneGlazedSugar";
      
      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:NSJSONWritingPrettyPrint ed 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 = [NSPropertyListSerializat ion 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
2,XMLWriter      https://github.com/ahmyi/XMLWriter



下面连接是XML转换为Dictionary
https://github.com/nicklockwood/XMLDictionary
http://download.csdn.net/detail/p709723778/6706331
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值