Maria Maria - 3 months ago 15
iOS Question

JSON parsing with mantle

I want to parse this JSON: https://api.guildwars2.com/v1/world_names.json?lang=en
I use Mantle. So I made two classes: server and serverList.

//server.m:

@implementation GW2Server

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"serverID": @"id",
@"serverName": @"name",
};
}

+ (NSValueTransformer *)serverIDJSONTransformer
{
return [MTLValueTransformer reversibleTransformerWithBlock:^(NSString *stringFromJSON){
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
return [formatter numberFromString:stringFromJSON];
}];
}

+ (NSValueTransformer *)serverNameJSONTransformer
{
return [MTLValueTransformer reversibleTransformerWithBlock:^(NSString *stringFromJSON){
return stringFromJSON;
}];
}

@end


//serverList.m

@implementation GW2ServerList

+(NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"serverID": @"serverList.serverID",
@"serverName": @"serverList.serverName",
};
}

+ (NSValueTransformer *)serverListJSONTransformer
{
return [MTLValueTransformer mtl_JSONArrayTransformerWithModelClass:[GW2Server class]];
}

@end


The problem is when I try to use [MTLJSONAdapter modelOfClass:[GW2ServerList class] fromJSONDictionary:jSONDict error:NULL], looks like it can't work with JSON arrays. And my JSON actually is array. So how can I resolve this issue?
I could get JSON array and then parse every object in it with Mantle, but looks like there is a better way which I don't know.

UPD: it's obvious that the problem is in serverList which consist of a single array of "server" objects. But I don't know how to rewrite JSONKeyPathsByPropertyKey correctly for it (because there is no such object as array in JSON - it's array by itself or something like that).

Answer

Resolved! All I should do is to make dictionary from JSON array like this:

NSArray *jSONArray = [NSJSONSerialization JSONObjectWithData:data options:0
                                                                   error:NULL];
NSDictionary *jSONDict = @{@"serverList": jSONArray};

And then it will be possible to parse it as usual:

self.serverList = [MTLJSONAdapter modelOfClass:[GW2ServerList class]
                                        fromJSONDictionary:jSONDict
                                                     error:NULL];
Comments