JSONModel可选和忽略不受尊重

时间:2015-03-23 18:03:26

标签: ios json jsonmodel

我在头文件中有这些属性。

@property (copy, nonatomic) NSString<Optional>* guidId;
@property (copy, nonatomic) NSDate* created_at;
@property (copy, nonatomic) NSNumber<Ignore>* longitude;
@property (copy, nonatomic) NSNumber<Ignore>* latitude;
@property (copy, nonatomic) NSNumber* altitude;
@property (copy, nonatomic) NSNumber* relative_altitude;
@property (copy, nonatomic) NSNumber* value;
@property (copy, nonatomic) NSString<Optional>* scale;
@property (copy, readonly, nonatomic, getter=getReadingTypeDescription) NSString* name;
@property (assign, nonatomic) WEEReadingType readingType;
@property (copy, nonatomic) NSString* name;
@property (strong, nonatomic) NSMutableArray* location;

虽然很奇怪,但可选并且忽略Ignore。

在实现文件中,我重写了这两个方法。

// This one because when converting to JSON from Model I need specific properties only and Ignore is not for this purpose

    - (NSString *)toJSONString
        {
        return [super toJSONStringWithKeys:
            @[
            @"guidId",
            @"location",
            @"altitude",
            @"relative_altitude",
            @"scale",
            @"name",
            @"value",
            @"created_at"
            ]];
        }


// And this one for the enum property that I want to ignore, but I found out I get an error when using [JSONModel arrayOfModelsFromDictionaries:json error:&error] that Optional or Ignore is not respected.

    + (BOOL)propertyIsIgnored:(NSString *)propertyName
        {
        if ([propertyName isEqualToString:@"readingType"] ||
            [propertyName isEqualToString:@"guidId"] ||
            [propertyName isEqualToString:@"longitude"] ||
            [propertyName isEqualToString:@"latitude"])
            {
            return YES;
            }
        return NO;
        }

JSON示例我需要转换为我的模型。

[
{
"created_at": "2015-03-20T19:26:28.000Z",
"location": [
40.70739851802653,
-74.005788154969
],
"altitude": 4.063048774263429,
"relative_altitude": 0.0,
"name": "pressure",
"value": 1014.718704223633,
"scale": "mb"
},
{
"created_at": "2015-03-20T19:26:28.000Z",
"location": [
40.70739851802653,
-74.005788154969
],
"altitude": 4.063048774263429,
"relative_altitude": 0.0,
"name": "pressure",
"value": 1014.718704223633,
"scale": null
}
]

以上[JSONModel arrayOfModelsFromDictionaries:json error:&error]将引发以下错误。

Error Domain=JSONModelErrorDomain Code=1 "Invalid JSON data: Value of required model key scale is null" UserInfo=0x170265cc0 {NSLocalizedDescription=Invalid JSON data: Value of required model key scale is null, kJSONModelKeyPath=[46].scale}

任何想法有什么不对?

2 个答案:

答案 0 :(得分:1)

尝试使用+(BOOL)propertyIsOptional:(NSString*)propertyName

答案 1 :(得分:0)

在.m文件中使用此功能

+(BOOL)propertyIsOptional:(NSString*)propertyName
{
    if([propertyName isEqualToString:@"somePropertyNameWhichShouldbeIgnored"])
       return YES;

    return NO;
}
相关问题