我定义了一些自定义类,例如TeacherStudent ...
现在,我从远程服务器接收教师信息(JSON字符串)。

如何将JSON字符串转换为Teacher对象。

在Java中,使用Teacher为所有类(Studentreflect ...)实现通用方法很容易。

但是在iOS上的Objective-C中,我能找到的最好方法是使用具有setValue:forKey方法的Core Data实体。首先,我将JSON字符串转换为NSDictionary,将非必需项中的键/值对设置为Entry

有没有更好的方法?

(我来自中国,所以可能我的英语不好,对不起!)

最佳答案

这些都是将JSON解析为字典或其他原语的良好框架,但是如果您希望避免做很多重复的工作,请查看http://restkit.org。具体来说,请查看https://github.com/RestKit/RestKit/blob/master/Docs/Object%20Mapping.md。这是对象映射的示例,其中您为Teacher类定义了映射,并且使用KVC将json自动转换为Teacher对象。如果您使用RestKit的网络调用,则过程是透明且简单的,但是我已经进行了网络调用,我需要将json响应文本转换为User对象(在您的情况下为Teacher),我终于弄清楚了如何。如果那是您的需要,请发表评论,我将与RestKit分享如何做。

注意:我将假定使用映射的约定{"teacher": { "id" : 45, "name" : "Teacher McTeacher"}}输出json。如果不是这种方式,而是像{"id" : 45, "name" : "Teacher McTeacher"}这样,那就不用担心...链接中的对象映射设计文档向您展示了如何执行此操作...一些额外的步骤,但还不错。

这是我从ASIHTTPRequest回调的

- (void)requestFinished:(ASIHTTPRequest *)request {
    id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:[request.responseHeaders valueForKey:@"Content-Type"]]; // i'm assuming your response Content-Type is application/json
    NSError *error;
    NSDictionary *parsedData = [parser objectFromString:apiResponse error:&error];
    if (parsedData == nil) {
        NSLog(@"ERROR parsing api response with RestKit...%@", error);
        return;
    }

    [RKObjectMapping addDefaultDateFormatterForString:@"yyyy-MM-dd'T'HH:mm:ssZ" inTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; // This is handy in case you return dates with different formats that aren't understood by the date parser

    RKObjectMappingProvider *provider = [RKObjectMappingProvider new];

    // This is the error mapping provider that RestKit understands natively (I copied this verbatim from the RestKit internals ... so just go with it
    // This also shows how to map without blocks
    RKObjectMapping* errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]];
    [errorMapping mapKeyPath:@"" toAttribute:@"errorMessage"];
    [provider setMapping:errorMapping forKeyPath:@"error"];
    [provider setMapping:errorMapping forKeyPath:@"errors"];

    // This shows you how to map with blocks
    RKObjectMapping *teacherMapping = [RKObjectMapping mappingForClass:[Teacher class] block:^(RKObjectMapping *mapping) {
        [mapping mapKeyPath:@"id" toAttribute:@"objectId"];
        [mapping mapKeyPath:@"name" toAttribute:@"name"];
    }];

    [provider setMapping:teacherMapping forKeyPath:@"teacher"];

    RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:provider];
    Teacher *teacher = nil;
    RKObjectMappingResult *mappingResult = [mapper performMapping];
    teacher = [mappingResult asObject];

    NSLog(@"Teacher is %@ with id %lld and name %@", teacher, teacher.objectId, teacher.name);
}

您显然可以对其进行重构以使其更整洁,但是现在可以解决我的所有问题..不再进行解析...只需响应->魔术->对象

关于iphone - 如何将JSON转换为对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8284123/

10-13 06:34