如何在NSString中检索JSON对象

时间:2013-05-08 09:23:54

标签: ios json

我有一个JSON,如: -

 {    
    author =     {
            class = "pocketapptest.Author";
            dateCreated = "2013-05-08T00:03:46Z";
            firstName = Kurt;
            id = 1;
            lastName = Vonnegut;
            lastUpdated = "2013-05-08T00:03:46Z";
        };
        class = "pocketapptest.Book";
        dateCreated = "2013-05-08T00:03:46Z";
        id = 1;
        lastUpdated = "2013-05-08T00:03:46Z";
        title = "Slaughterhouse Five";
    }

我可以访问dateceated / title as

NSString* title = [jsondata objectForKey:@"title"];

但我如何存储firstName / lastName等。

4 个答案:

答案 0 :(得分:0)

尝试这样,你可以得到如下的值

 NSString* firstName = [[jsondata objectForKey:@"author"]objectForKey:@"firstName"];

答案 1 :(得分:0)

我猜你可能只使用jsondata objectForKey:两次。就像那样:

NSString* firstName = [[jsondata objectForKey:@"author"]objectForKey:@"firstName"];

希望有所帮助

答案 2 :(得分:0)

使用ivars创建一个类来存储来自JSON的数据

@interface MyDetails

@property(nonatomic, retain) NSString *class, *dateCreated, *firstName,*ID, *lastName, *lastUpdated;
@end

@implementation MyDetails

@synthesize class, dateCreated, firstName, ID, lastName, lastUpdated;

@end

为mydetails分配实例

 MyDetails *mydetails = [MyDetails alloc]init];

 mydetails.class = [[jsondata objectForKey:@"author"]objectForKey:@"class"];
 mydetails.dateCreated = [[jsondata objectForKey:@"author"]objectForKey:@"dateCreated"];
 mydetails.firstName = [[jsondata objectForKey:@"author"]objectForKey:@"firstName"];
 mydetails.ID = [[jsondata objectForKey:@"author"]objectForKey:@"id"];
 mydetails.lastName = [[jsondata objectForKey:@"author"]objectForKey:@"lastName"];
 mydetails.lastUpdated = [[jsondata objectForKey:@"author"]objectForKey:@"lastUpdated"];

答案 3 :(得分:0)

您的JSON无效。首先使用有效的JSON 。您可以检查您的JSON是否有效here

然后从json访问字符串对象。

希望它对你有所帮助。