IOS開發之----NSDictionary,JSON和XML互相轉換

本文永久地址爲 http://www.cnblogs.com/ChenYilong/p/4044521.html,轉載請註明出處。html

 

 

-(void)test {git

    //XML文本範例github

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

    

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

    // 解析XMLNSDictionaryspa

    NSError *parseError = nil;.net

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

    // 打印 NSDictionaryorm

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

    

    //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,轉載請註明出處。

相關文章
相關標籤/搜索