Objective-C Json 实例详解
Objective-CJson实例详解
通过使用NSJSONSerialization可以Json与Foundation的相互转换。下面具体介绍Objective-cjson的使用。
JsonToFundation
使用JSONObjectWithData可以将Json转化为Foundation。Json的顶层可以是{}或[]因此可以有NSDictionary和NSArray两种格式。读取使用ObjectForKey返回对应的对象。
NSString*items=@"{"items":["item0","item1","item2"]}";
NSData*data=[itemsdataUsingEncoding:NSUTF8StringEncoding];
NSError*error=nil;
idjsonObject=[NSJSONSerializationJSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
if([jsonObjectisKindOfClass:[NSDictionaryclass]]){
NSDictionary*dictionary=(NSDictionary*)jsonObject;
NSLog(@"DersializedJSONDictionary=%@",dictionary);
}elseif([jsonObjectisKindOfClass:[NSArrayclass]]){
NSArray*nsArray=(NSArray*)jsonObject;
NSLog(@"DersializedJSONArray=%@",nsArray);
}else{
NSLog(@"AnerrorhappenedwhiledeserializingtheJSONdata.");
}
NSDictionary*dict=(NSDictionary*)jsonObject;
NSArray*arr=[dictobjectForKey:@"items"];
NSLog(@"listis%@",arr);
FundationToJson
使用dataWithJsonObject可以将Fundation转换为Json。其中options:NSJSONWritingPrettyPrinted是分行输出json,无空格输出使用option:kNilOptions。
下面这段代码是IOS内购获取商品列表。获取后,将内容添加到Json中。
NSArray*myProduct=response.products;
NSDictionary*myDict;
NSMutableDictionary*dict=[NSMutableDictionary
dictionaryWithCapacity:4];
for(inti=0;i<myProduct.count;++i)
{
//NSLog(@"----------------------");
//NSLog(@"Producttitle:%@",[myProduct[i]localizedTitle]);
//NSLog(@"Productdescription:%@",[myProduct[i]localizedDescription]);
//NSLog(@"Productprice:%@",[myProduct[i]price]);
//NSLog(@"Productid:%@",[myProduct[i]productIdentifier]);
myDict=[NSDictionarydictionaryWithObjectsAndKeys:
[myProduct[i]localizedTitle],@"title",
[myProduct[i]localizedDescription],@"desc",
[myProduct[i]price],@"price",
[myProduct[i]productIdentifier],@"product",nil];
[dictsetValue:myDictforKey:[myProduct[i]productIdentifier]];
}
if([NSJSONSerializationisValidJSONObject:dict])
{
NSError*error;
NSData*str=[NSJSONSerializationdataWithJSONObject:dict
options:kNilOptionserror:&error];
NSLog(@"Result:%@",[[NSStringalloc]initWithData:str
encoding:NSUTF8StringEncoding]);
}
else
{
NSLog(@"AnerrorhappenedwhileserializingtheJSONdata.");
}
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
