将JSON数组转换为NSDictionary后,我该怎么办?

时间:2013-10-10 03:10:46

标签: ios objective-c arrays json nsdictionary

我需要以下列格式解析JSON数组:

[
 {
  name: "10-701 machine learning",
  _id: "52537480b97d2d9117000001",
  __v: 0,
  ctime: "2013-10-08T02:57:04.977Z"
 },
 {
  name: "15-213 computer systems",
  _id: "525616b7807f01fa17000001",
  __v: 0,
  ctime: "2013-10-10T02:53:43.776Z"
 }
]

因此在获得NSData之后,我将其转移到NSDictionary:

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(@"%@", dict);

但是从控制台查看,我认为字典实际上是这样的:

(
        {
        "__v" = 0;
        "_id" = 52537480b97d2d9117000001;
        ctime = "2013-10-08T02:57:04.977Z";
        name = "10-701 machine learning";
    },
        {
        "__v" = 0;
        "_id" = 525616b7807f01fa17000001;
        ctime = "2013-10-10T02:53:43.776Z";
        name = "15-213 computer systems";
    }
)

外面的括号是什么意思?我应该如何进一步将这个NSDictionary转移到一些课程对象的NSArray或NSMutableArray(我自己定义,尝试表示JSON数组的每个元素)?

2 个答案:

答案 0 :(得分:2)

使用此代码,

NSArray *array = [NSJSONSerialization JSONObjectWithData: responseData options:NSJSONReadingMutableContainers error:&error];
NSDictionary *dict = [array objectAtIndex:0];

然后您可以通过以下代码

来检索值
NSString *v = [dict objectForKey:@"__v"];
NSString *id = [dict objectForKey:@"_id"];
NSString *ctime = [dict objectForKey:@"ctime"];
NSString *name = [dict objectForKey:@"name"];

答案 1 :(得分:0)

括号只是NSDictionary输出格式的结果与JSON的格式不完全相同。您的代码仍然成功地将JSON转换为NSDictionary对象。

我认为你真正想要的是一系列字典。像这样:

NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *firstObject = [json objectAtIndex:0];

在此之后,firstObject将包含:

{
    "__v" = 0;
    "_id" = 52537480b97d2d9117000001;
    "ctime" = "2013-10-08T02:57:04.977Z";
    "name" = "10-701 machine learning";
}

您可以使用objectForKey:

检索信息
NSString *time = [firstObject objectForKey:@"ctime"];
// time = "2013-10-08T02:57:04.977Z"

希望有所帮助。