简单介绍JSON和XML

JSON:

JSON与oc对象可以相互转化

最常见的是JSON与数组之间的转化:

数组转化为JSON

 NSDictionary *dic=@{@"name":@"lisi",@"age":@24,@"weight":[NSNull null]};

    NSLog(@"%@",dic);

    //JSONOC对象之间的相互转换

    //isValidJSONObject判断SONObject(NSDictionary,NSArray)是否有效

    //options:NSJSONWritingPrettyPrinted 显示可读Json字符串

    if ([NSJSONSerialization isValidJSONObject:dic]) {

        NSData *data=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];

        NSString *strJSON=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"JSON:%@",strJSON);

    }

JSON转化为数组

 NSString*strJSON2=@{\"name\":\"lisi\",\"age\":28,\"weight\":null}";

 NSData *data2=[strJSON2 dataUsingEncoding:NSUTF8StringEncoding];


 NSDictionary *dic2=[NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingAllowFragments error:nil];

    NSLog(@"oc:%@",dic2);

xml:

1.可扩展标记语言

2.设计宗旨是传输数据,而非显示数据

3.xml必须有根元素

4.必须嵌套正确

5.属性值必须加双引号

6.一些特殊符号必须转换为实体

xml命名规则:

1.可以含字母,数字以及其他字符

2.不能以数字或者标点符号开始

3.不能以字符“xml”(或者XM、Xml)开始

如下是一种简单的XML:

<?xml version="1.0" encoding="utf-8"?>


<Student id="1001" type="1">

<!--注释-->

   <Name>zhangsan</Name>

   <Age>18</Age>

   <Gender>female</Gender>

   <Weight>130</Weight>

   <Languages>

      <Language type="英语">Language </Language>

      <Language type="日语">Language </Language>

      <Language type="德语">Language </Language>

   </Languages>

</Student>

//解析xml

    //xml保存的路径(就是上面那个xml)

    _xmlpath=@"/Users/apple/Desktop/test.xml";

    //通过XMLDictionaryParser设置值

    //单例模式,设置解析器

    //step1.设置解析器

    XMLDictionaryParser *xmlParser=[XMLDictionaryParser sharedInstance];

    //显示所有的节点名

    xmlParser.nodeNameMode=XMLDictionaryNodeNameModeAlways;

    //属性字典

  xmlParser.attributesMode=XMLDictionaryAttributesModeDictionary;

    xmlParser.preserveComments=YES;

    //step2:解析xml

    NSDictionary *_dicxml=[NSDictionary dictionaryWithXMLFile:_xmlpath];

    NSLog(@"%@",_dicxml);

    NSLog(@"当前节点名字:%@",[_dicxml nodeName]);

    NSDictionary *dict=[_dicxml attributes];

    NSLog(@"%@",dict);

    

    NSDictionary *dicLanguage=[_dicxml objectForKey:@"Languages"];

    NSLog(@"Language:%@",[dicLanguage nodeName]);

    //读取注释

    //NSArray *temp=_dicxml.comments;

    NSLog(@"%@",[_dicxml comments]);


转载于:https://my.oschina.net/u/2529338/blog/549190

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值