2013-11-14 99 views
1

我有这个在我的SongModel.h:JSONModel接受对象和字符串

@interface SongModel : JSONModel 
@property (strong, nonatomic) NSString *title; 
@property (strong, nonatomic) NSString *artist; 
@property (strong, nonatomic) NSDate *start; 
@property (strong, nonatomic) NSDate *end; 
@property (strong, nonatomic) NSString<Optional> *artistLink; 
@property (strong, nonatomic) NSString<Optional> *songLink; 
@end 

因为artistLink和songLink没有得到很好格式化(不是我)JSON。 它可以是一个字符串或一个空的对象,我怎么解析这个?

的“ID”的类型不是JSONModel

回答

0

我可能会接受并id那么它要么设置为[NSNull null]时,它无法解析,或将其设置为NSString时,它能够被支持。

@property (strong, nonatomic) id artistLink;

if (canBeParsed) { 
    artistLink = @"The string"; 
} else { 
    artistLink = [NSNull null]; 
} 

编辑:马丁河养育了一个好点的,和多数民众赞成这样做肯定的另一种方式。

@property (strong, nonatomic) NSString *artistLink

if (canBeParsed) { 
    artistLink = @"The string"; 
} else { 
    artistLink = nil; 
} 
+1

正确答案。 – Tirth

+1

如果不能解析对象,为什么不声明为'NSString *'并将其设置为'nil'?这允许更好的编译器检查字符串属性何时被访问。 –

+0

我是新来的目标C和遵循很多教程,但我怎么能做到这样的事情?现在说JSONModel不支持SongModel.artistLink的属性类型。 我发现这个源在Github上: //不允许此类型 - 程序员mistaked - >例外 @throw [NSException exceptionWithName:@ “JSONModelProperty类型不允许” 原因:[的NSString stringWithFormat:@“属性类型% @。%@不受JSONModel支持。“,self.className,p.name] userInfo:nil]; –

0

我固定它通过:

NSRegularExpression *replaceEmptyObject = [NSRegularExpression regularExpressionWithPattern:@"{}/g" options:0 error:nil]; 
jsonString = [replaceEmptyObject stringByReplacingMatchesInString:jsonString options:0 range:NSMakeRange(0, [jsonString length]) withTemplate:@"\"\""]; 

也许不是最美丽的方式,但它为我工作。 这些是这个json中唯一的空对象。