ios 开发JSON and NULL values errors

Published on in IOS开发 with 33 views and 0 comments

当我们使用 AFNetworking 框架进行网络请求时候,经常会解析json结果,但是json中含有null时会报错

2014-06-11 07:11:56.829 [494:6107] LabelValue is =====> 2014-06-11 07:11:56.830[494:613] -[NSNull length]: unrecognized selector sent to instance 0x101b56b50 
2014-06-11 07:11:56.846[494:613] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull length]: unrecognized selector sent to instance 0x101b56b50' *** First throw call stack: BLA BLA BLA

返回的json结果为

{
	dateAdded = "2014-04-22T16:50:32Z";
	eventDate = "<null>"; //This is the issue 
	id = 71496;
	name = Test;
	ownerName = "name";
	webLink = "someurl";
},

解决方法如下

if (eventDate == (id)[NSNull null]) {
 // eventDate is null 
} 

or you can do:

if (eventDate != (id)[NSNull null]) {
 // eventDate is not null // you are free to parse it :) 
}
说你懂得生之微末,我便做了这壮大与你看,你说再热闹也终需离散,我便做了这一辈子与你看,你说冷暖自知,我便做了这冬花夏雪与你看,你说恋恋旧日好时光,我便做了这描金绣凤的浮世绘与你看。你说应愁高处不胜寒,我便拱手河山,讨你欢。