【发布时间】:2016-05-25 15:35:39
【问题描述】:
我正在尝试使用框架 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 时,作为 responseObject 从服务器获取的数据,数据显示为 nil:
for (NSArray *array in [responseObject valueForKey:@"sections"]) {
NSArray *seccionArray = [MTLJSONAdapter modelsOfClass:[Section class] fromJSONArray:array error:nil];
}
我尝试了很多方法来很好地解析这些数据,但应用程序总是崩溃或返回 nil。我希望你能帮我解决这个问题
【问题讨论】:
-
你不能用iOS吗?
NSJSONSerialization? -
我试过了,但是应用崩溃了。
标签: ios objective-c json