jubilee

Programing, Books and more...

JSONからデータを取得する方法

以下のようなJSONデータから指定したデータを取得する方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
meta = 
{
    method = POST;
    url = "/app/ApiPosts/post.json";
};
response =    /// (1)
{
    "comment_id" = 144;   /// (2)
    "video_id" = 144;
    Adviser = {
        name = "<null>";
    };
    Post = {
        "adviser_id" = "-1";
        "video_id" = 144;   /// (3)
    };
    User = {
        id = 1;
        username = taro;
    };
    Comments =  /// ここは配列でComment-Videoが1セットで複数セットくる
    (
        {
            Comment = {
                comment = "\U305d\U305d\U305d\U305d\n";   /// (4)
                id = 144;
            };
            Video = {
                hash = 266d1a0ccabc501149322446e49e274a;    /// (4)
                id = 144;
            };
        }
    );
};

(1) response = 以下のデータを取得

1
NSDictionary *responseDataDic = (NSDictionary*)responseObject[@"response"];

(2) comment_idのデータを取得

1
NSLog(@"commnt_id : %@", responseDataDic[@"comment_id"]);

(3) Post の video_idのデータを取得

1
NSLog(@"Post video_id: %@", responseDataDic[@"Post"][@"video_id"]);

(4) Commentsの中のComment-commentとVideo-hashを取得

1
2
3
4
5
/// 高速列挙で辞書に抜き出し
for (NSDictionary *dic in responseDataDic[@"Comments"]) {
    NSLog(@"Comment id: %@", dic[@"Comment"][@"id"]);
    NSLog(@"Video id: %@", dic[@"Video"][@"id"]);
}

もしくは2ステップで

1
2
3
4
5
6
7
8
9
10
11
/// 可変配列を用意
NSMutableArray *array = [NSMutableArray array];
/// 高速列挙でComments部分を辞書に抜き出し、それを可変配列に追加
for (NSDictionary *dic in responseDataDic[@"Comments"]) {
    [array addObject:dic];
}
/// 可変配列から辞書に抜き出し
for (NSDictionary *dic in array) {
    NSLog(@"Comment id: %@", dic[@"Comment"][@"id"]);
    NSLog(@"Video id: %@", dic[@"Video"][@"id"]);
}