JSON&&XML
JSON
1、全称:JavaScript Object Notation
2、from dictionary to JSON string
//creat a dictionary
NSDictionary *jsonDic = @{
@"name":@"weizh",
@"age":@24,
@"gender":@"male",
@"weight":@140
};
//creat jsonData with jsonSerialization
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:nil];
//switch to string and print
NSString *jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"jsonStr:%@",jsonStr);
print information:
jsonStr:{
"age" : 24,
"gender" : "male",
"weight" : 140,
"name" : "weizh"
}
3、from JSON to dictionary
//get data from JSON file
NSData *jsonData = [NSData dataWithContentsOfFile:@"/Users/customer/desktop/test.json"];
//switch JSON data to OC class
NSError *error;
id obj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSLog(@"obj:%@",obj);
XML
1、全称:EXtensible Markup Language 扩展文本标记语言
2、XMLDictionary parse the XML
XMLDictionaryParser *parser = [XMLDictionaryParser sharedInstance];
//creat dicitonary by xml dictionary parser (dictionary categary added in XMLDictionary file)
NSDictionary *xmlDic = [parser dictionaryWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
NSLog(@"xmlDic:%@",xmlDic);
3、switch dictionary to XML string
NSDictionary *xmlDic = @{
@"__name":@"Person",
@"__attributes":@{@"id":@"123",@"class":@"hello"},
@"name":@"weizh",
@"age":@24,
@"gender":@"male",
@"height":@1.74
};
NSString *xmlStr = [xmlDic XMLString];
NSLog(@"xmlStr: %@",xmlStr);
print information:
xmlStr:
<Person id="123" class="hello">
<age>24</age>
<gender>male</gender>
<name>weizh</name>
<height>1.74</height>
</Person>