iOS基础知识:Objective-C 之 JSON&XML

本文探讨了iOS开发中Objective-C对JSON和XML的处理。介绍了JSON的含义,从字典转JSON字符串的方法,以及如何将JSON转换回字典。同时,概述了XML的全称——扩展文本标记语言,讲解了使用XMLDictionary解析XML的过程,以及如何将字典转换为XML字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值