使用RestKit 0.20.3映射json

时间:2013-08-12 16:54:20

标签: ios json parsing mapping restkit-0.20

我正在尝试通过RestKit 0.20.3映射对象,但我知道这些日志已经知道了:

2013-08-12 18:32:08.158 MyAppIphone[848:5703] E restkit.network:RKResponseMapperOperation.m:304 Failed to parse response data: Loaded an unprocessable response (200) with content type 'application/json'

2013-08-12 18:32:08.174 MyAppIphone[848:5703] E restkit.network:RKObjectRequestOperation.m:238 POST 'myUrl' (200 OK / 0 objects) 

[request=0.1305s mapping=0.0000s total=5.6390s]:
error=Error Domain=org.restkit.RestKit.ErrorDomain Code=-1017 "Loaded an unprocessable response (200) with content type 'application/json'" 

UserInfo=0x1ed5a500 {NSErrorFailingURLKey=myUrl, NSUnderlyingError=0x1ed5b240 "The operation couldn’t be completed. (Cocoa error 3840.)", NSLocalizedDescription=Loaded an unprocessable response (200) with content type 'application/json'}

response.body={"my json content"}

这是MyData类:

#import <Foundation/Foundation.h>

@interface MyData : NSObject

@property (nonatomic, retain) NSString *criterias;

@end

以下是我设置mapper的方法:

- (RKResponseDescriptor*) getDataMapping
{
    // Mapping
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[MyData class]];
    [mapping addAttributeMappingsFromDictionary:@{
     @"criteriasHeader":        @"criteriasHeader"
     }];

    // Status code
    NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);

    // Descriptior
    return [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodPOST pathPattern:nil keyPath:@"regions" statusCodes:statusCodes];
}

这是我的请求功能:

- (void) runRequestWithType:(RequestType)type baseUrl:(NSString *)baseUrlString path:(NSString *)path parameters:(NSDictionary *)parameters mapping:(RKResponseDescriptor *) descriptor
{
    // Print heeader and body from the request and the response
    RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
    RKLogConfigureByName("Restkit/Network", RKLogLevelDebug);
    RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace);
    RKLogConfigureByName("Restkit/ObjectMapping", RKLogLevelDebug);

    // Set up the base url
    NSURL *baseUrl = [NSURL URLWithString:baseUrlString];

    //Run request in block
    RKObjectManager *manager = [RKObjectManager managerWithBaseURL:baseUrl];
    [manager addResponseDescriptorsFromArray:@[descriptor]];

    [manager.router.routeSet addRoute:[RKRoute routeWithClass:[MyData class] pathPattern:path method:RKRequestMethodPOST]];
    //[manager getObjectsAtPath:path parameters:parameters success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    [manager postObject:nil path:path parameters:parameters success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
        if ([self.delegate respondsToSelector:@selector(requestDidSucceedWithType:andResponse:)]) {
            [self.delegate requestDidSucceedWithType:type andResponse:[mappingResult firstObject]];
        }
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        if ([self.delegate respondsToSelector:@selector(requestDidFailWithError:andError:)]) {
            [self.delegate requestDidFailWithType:type andError:error];
        }
    }];
}

PS:我尝试使用更短的JSON,效果很好。

我做错了吗?

你能帮助我吗,谢谢。

2 个答案:

答案 0 :(得分:1)

这种错误来自RK下的JSON映射。默认是使用封装在RKNSJSONSerialization中的NSJSONSerialization。你可以在那里放一个断点,以找出更多关于错误的信息。 到目前为止我找到了2个来源:

  • NSJSONSerialization不喜欢非UTF8数据。确保您从服务器接收它,或修改RK以从数据到字符串(具有正确的编码)正确转换为UTF8数据(到目前为止最好的方式)。如果使用CoreData,您可以在第586行查看RKManagedObjectRequestOperation。
  • iOS5中的
  • 存在错误。最简单的修复是使用另一个解析库

答案 1 :(得分:1)

希望您能够将JSON的服务器编码更改为UTF-8。

如果没有,您可以通过替换Restkit中的默认JSON mime类型处理程序来解决此问题。使用Restkit类RKNSJSONSerialization作为参考。

在自定义JSON mime类型处理程序中,在执行与RKNSJSONSerialization类相同的操作之前,执行从传入编码(在ISO-8859-1下面的示例中)到UTF-8的数据转换。

@implementation MyCustomJSONSerializer    

+ (id)objectFromData:(NSData *)data error:(NSError **)error
{
    NSString* latin = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSISOLatin1StringEncoding];

    NSData* utf8 = [latin dataUsingEncoding:NSUTF8StringEncoding];

    return [NSJSONSerialization JSONObjectWithData:utf8 options:0 error:error];
}

@end

如果必须以非UTF-8编码将数据POST回服务器,则可以对dataFromObject方法执行类似操作。

现在,您可以在初始化Restkit之后添加此自定义处理程序,它将与默认(UTF-8)一起使用:

[RKMIMETypeSerialization registerClass:[MyCustomJSONSerializer class] forMIMEType:RKMIMETypeJSON];