码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2014-10-22 23:27:42      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   os   ar   for   

本文永久地址为 http://www.cnblogs.com/ChenYilong/p/4044521.html,转载请注明出处。

?

?

-(void)test {

? ? //XML文本范例

? ? NSString *testXMLString = @"Cake0.55RegularChocolateBlueberryNoneGlazedSugar";

?? ?

? ? NSLog(@"xml string[\n%@\n]", testXMLString);

? ? // 解析XMLNSDictionary

? ? NSError *parseError = nil;

? ? NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:testXMLString error:&parseError];

? ? // 打印 NSDictionary

? ? NSLog(@"%@", xmlDictionary);

?? ?

? ? //NSDictionary转换为Data

? ? NSData* jsonData = [NSJSONSerializationdataWithJSONObject:xmlDictionary options:NSJSONWritingPrettyPrintederror:&parseError];

?? ?

? ? //Data转换为JSON

? ? NSString* str = [[NSStringalloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

?? ?

? ? NSLog(@"jsonData string[\n%@\n]", str);

? ? //字符组转换为NSDictionary

? ? NSDictionary *jsonDict = [str objectFromJSONString];

?? ?

? ? //NSDictionary转换为XMLplist格式

? ? NSData *xmlData = [NSPropertyListSerializationdataFromPropertyList:jsonDict

?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? format:NSPropertyListXMLFormat_v1_0

?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? errorDescription:NULL];

?? ?

? ? //Data转换为NSString输出 编码为UTF-8

? ? NSLog(@"XML: %@", [[NSStringalloc] initWithData:xmlData encoding:NSUTF8StringEncoding]);

?? ?

?? ?

?? ?

? ? NSLog(@"%@",[XMLWriter XMLStringFromDictionary:jsonDict withHeader:NO]);

?? ?

}

?

//其中用到了三个类库,分别为

1JSONKit ? ? ? https://github.com/johnezang/JSONKit

2XMLWriter? ? https://github.com/ahmyi/XMLWriter

3XMLReader ? https://github.com/amarcadet/XMLReader

?

源码下载地址:http://download.csdn.net/download/p709723778/5725585

?

?

下面连接是XML转换为Dictionary

https://github.com/nicklockwood/XMLDictionary

http://download.csdn.net/detail/p709723778/6706331

?

?

本文永久地址为?http://www.cnblogs.com/ChenYilong/p/4044521.html,转载请注明出处。

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

标签:des   style   blog   http   color   io   os   ar   for   

原文地址:http://www.cnblogs.com/ChenYilong/p/4044521.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!