簡體   English   中英

如何將JSON轉換為Object

[英]How to convert JSON to Object

我定義了一些自定義類,例如TeacherStudent ...現在我從遠程服務器接收教師信息(JSON字符串)。

如何將JSON字符串轉換為Teacher對象。

在Java中,使用reflect可以很容易地為所有類( TeacherStudent ...)實現一個通用方法。

但是在iOS上的Objective-C中,我能找到的最好的方法是使用具有setValue:forKey方法的核心數據實體。 首先,我將JSON字符串轉換為NSDictionary ,將dectionary中的鍵值對設置為Entry

有沒有更好的方法?

(我來自中國,也許我的英語很差,對不起!)

首先,你使用JSON Parser嗎? (如果沒有,我建議使用SBJson)。

其次,為什么不在自定義類中創建一個返回self對象的initWithDictionary init方法呢?

這些都是JSON解析字典或其他原語的好框架,但是如果你想避免做大量的重復性工作,請查看http://restkit.org 具體來說,請查看https://github.com/RestKit/RestKit/blob/master/Docs/Object%20Mapping.md這是對象映射的示例,您可以在其中定義Teacher類的映射,並將json自動轉換為使用KVC的教師對象。 如果你使用RestKit的網絡調用,這個過程都是透明和簡單的,但我已經進行了網絡調用,我需要的是將我的json響應文本轉換為User對象(你的教師),我終於想通了怎么樣。 如果這就是你需要的,發表評論我會與RestKit分享如何做到這一點。

注意:我將假設使用映射約定輸出json {"teacher": { "id" : 45, "name" : "Teacher McTeacher"}} 如果不是這樣,而是像這樣{"id" : 45, "name" : "Teacher McTeacher"}然后不要擔心...鏈接中的對象映射設計doc告訴你如何做到這一點......一些額外的步驟,但不是太糟糕。

這是我從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);
}

你可以明顯地重構它以使它更清潔,但現在解決了我所有的問題..不再解析...只是響應 - >魔術 - >對象

具體來說,請查看https://github.com/fanpyi/jsontooc/blob/master/README.md這是將JSON數據轉換為Objective-C模型的示例,使用nodejs。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM