我正在尝试使用框架Mantle解析从服务接收的数据。json 有嵌套数据,我在解析它时遇到问题。json 如下所示:
{
"sections": [
{
"title": "title1",
"level": 1,
"content": [
{
"type": "type1",
"text": "text1"
}
],
"images": []
},
{
"title": "title2",
"level": 2,
"content": [
{
"type": "type2",
"text": "text2"
},
{
"type": "type9",
"text": "text9"
},
{
"type": "type4",
"text": "text4"
},
{
"type": "type6",
"text": "text6"
}
],
"images": [
{
"src": "http://cvbcvcv",
"caption": "caption"
}
]
}]
}
我使用的类是:
// MainObject.h
@interface MainObject : MTLModel <MTLJSONSerializing>
@property (strong, nonatomic) NSArray *sectionsArray;
+ (NSValueTransformer *)sectionsArrayJSONTransformer;
@end
@interface Section : MTLModel <MTLJSONSerializing>
@property (strong, nonatomic) NSString *title;
@property (assign, nonatomic) NSString *level;
@property (strong, nonatomic) NSArray *content;
@property (strong, nonatomic) NSArray *images;
+ (NSValueTransformer *)contentJSONTransformer;
+ (NSValueTransformer *)imagesJSONTransformer;
@end
@interface Content : MTLModel <MTLJSONSerializing>
@property (strong, nonatomic) NSString *type;
@property (strong, nonatomic) NSString *text;
@end
@interface Image : MTLModel <MTLJSONSerializing>
@property (strong, nonatomic) NSString *src;
@property (strong, nonatomic) NSString *caption;
@end
和
//MainObject.m
@implementation MainObject
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"sectionsArray" : @"sections",};
}
+ (NSValueTransformer *)sectionsArrayJSONTransformer
{
return [MTLJSONAdapter dictionaryTransformerWithModelClass:[Section class]];
}
@end
@implementation Section
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"title" : @"title",
@"level" : @"level",
@"content" : @"content",
@"images" : @"images",};
}
+ (NSValueTransformer *)contentJSONTransformer
{
return [MTLJSONAdapter arrayTransformerWithModelClass:[Content class]];
}
+ (NSValueTransformer *)imagesJSONTransformer
{
return [MTLJSONAdapter arrayTransformerWithModelClass:[Image class]];
}
@end
@implementation Content
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"type" : @"type",
@"text" : @"text",};
}
@end
@implementation Image
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"src" : @"src",
@"caption" : @"caption",};
}
@end
然后,当我调用服务并尝试使用以下代码解析 json 时,响应对象从服务器获得的数据,数据显示为 nil:
for (NSArray *array in [responseObject valueForKey:@"sections"]) {
NSArray *seccionArray = [MTLJSONAdapter modelsOfClass:[Section class] fromJSONArray:array error:nil];
}
我已经尝试了很多方法来很好地解析这些数据,但应用程序总是崩溃或返回 nil。我希望你能帮助我解决这个问题
为什么不能只使用一行NSJSONSerialization
?
NSMutableDictionary *yourArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
然后你从数组中获取你想要的东西...