如何将JSON转换为对象

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

如何将JSONstring转换为Teacher对象。

在Java中,很容易实现所有类( TeacherStudent …)的通用方法。

但是在iOS上的Objective-C中,我能find的最好的方法是使用核心数据实体,它具有setValue:forKey方法。 首先,我将JSONstring转换为NSDictionary ,将string中的键值对设置为Entry

有没有更好的方法?

(我来自中国,也许我的英文很差,对不起!)

这些都是JSONparsing字典或其他原语的良好框架,但如果您希望避免做大量的重复性工作,请查看http://restkit.org 。 具体来说,检查出https://github.com/RestKit/RestKit/blob/master/Docs/Object%20Mapping.md这是对象映射的例子,你为你的教师类定义映射,并将json自动转换为通过使用KVC的教师对象。 如果你使用RestKit的networking调用,这个过程是透明和简单的,但我已经有了我的networking调用,我需要的是将我的JSON响应文本转换为一个用户对象(老师在你的情况),我终于想通了怎么样。 如果这是你所需要的,发表评论,我会分享如何用RestKit做到这一点。

注意:我将假设使用映射约定{"teacher": { "id" : 45, "name" : "Teacher McTeacher"}}输出json。 如果不是这样,而是像这样{"id" : 45, "name" : "Teacher McTeacher"}那么别担心…链接中的对象映射devise文档显示如何做到这一点…几个额外的步骤,但不是太糟糕。

这是我从ASIHTTPRequest的callback

 - (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); } 

你显然可以重构这个,使其更清洁,但现在解决了我所有的问题..没有更多的parsing…只是响应 – >魔术 – >对象

首先,你使用JSONparsing器吗? (如果没有,我会推荐使用SBJson)。

其次,为什么不在自定义类中创build一个initWithDictionary初始化方法来返回自己的对象呢?