0

我需要解析以下格式的 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 转移到一些 Course 对象的 NSArray 或 NSMutableArray (我自己定义的,尝试表示 JSON 数组的每个元素)?

4

2 回答 2

2

Use this code,

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

Then you can retrieve the values by following code,

NSString *v = [dict objectForKey:@"__v"];
NSString *id = [dict objectForKey:@"_id"];
NSString *ctime = [dict objectForKey:@"ctime"];
NSString *name = [dict objectForKey:@"name"];
于 2013-10-10T03:19:53.163 回答
0

The parenthesis are just the result of NSDictionary output format not being exactly the same thing as how JSON is formatted. Your code still successfully converted the JSON into a NSDictionary object.

I think what you really want, though, is an array of dictionaries. Something like this:

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

After this, firstObject would contain:

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

And you can retrieve the information with objectForKey:

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

Hope that helps.

于 2013-10-10T03:20:04.910 回答