【问题标题】:JSONModel accept Object and StringJSONModel 接受对象和字符串
【发布时间】:2013-11-14 17:46:48
【问题描述】:

我的 SongModel.h 中有这个:

@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 中格式不正确。 可以是字符串也可以是空对象,如何解析?

JSONModel 不支持“id”类型

【问题讨论】:

    标签: objective-c xcode macos jsonmodel


    【解决方案1】:

    我可能会接受id,然后在无法解析时将其设置为[NSNull null],或者在可以解析时将其设置为NSString

    @property (strong, nonatomic) id artistLink;

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

    编辑:Martin R. 提出了一个很好的观点,这当然是另一种方式。

    @property (strong, nonatomic) NSString *artistLink

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

    【讨论】:

    • 如果无法解析对象,为什么不声明为NSString * 并设置为nil?这允许在访问字符串属性时更好地检查编译器。
    • 我是 Objective c 的新手,并且学习了很多教程,但是我怎样才能完成这样的事情呢?它现在说 JSONModel 不支持 SongModel.artistLink 的属性类型。我在 Github 上的源代码中找到了这个://type not allowed - 程序员弄错了 -> exception @throw [NSException exceptionWithName:@"JSONModelProperty type not allowed" reason:[NSString stringWithFormat:@"Property type of %@.%@ is JSONModel 不支持。", self.className, p.name] userInfo:nil];
    【解决方案2】:

    我通过以下方式修复它:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      相关资源
      最近更新 更多