help me to parse JSON value using JSONTouch

后端 未结 2 1086
-上瘾入骨i
-上瘾入骨i 2021-01-26 12:57

I have the following json:

http://www.adityaherlambang.me/webservice.php?user=2&num=10&format=json

I would like to get all the name in this data by the f

相关标签:
2条回答
  • 2021-01-26 13:45

    It seems to me that when you create the "users" dictionary you are actually creating a "user" dictionary.

     NSDictionary *users = [[results objectForKey:@"users"] objectForKey:@"user"];//crating users dictionary with 1 "user" inside.
    

    EDIT

    in second view. why don't you just iterate the "result" dictionary? like that -

     for (NSDictionary *user in result){
      //NSLog(@"key:%@, value:%@", user, [user objectForKey:user]);
      NSString *title = [users objectForKey:@"NAME"];
      NSLog(@"%@", title);
     }
    

    hope it will help shani

    0 讨论(0)
  • 2021-01-26 13:54
    NSDictionary *results = [responseString JSONValue];
    
    NSDictionary *users = [results objectForKey:@"users"] objectForKey:@"user"];
    
    1. The JSON data has an array as its top level value. It’s not a JSON object, hence it’s not a dictionary. This is why you get the -[__NSArrayM objectForKey:]: unrecognized selector sent to instance exception.
    2. There is no "users" entry in your JSON data.
    3. The code above doesn’t compile.

    The first step is to understand your JSON data. It is structured as follows:

    1. the top level value is an array
    2. each element in the array is an object/dictionary with a single key called "user"
    3. the value of the "user" key is itself another object/dictionary with various key-value pairs

    If you want to iterate over the users and print the value for the "NAME" key, follow the example below.

    NSString *responseString = [[NSString alloc] initWithData:responseData
        encoding:NSUTF8StringEncoding];
    
    // 1. the top level value is an array
    NSArray *results = [responseString JSONValue];
    
    // 2. each element in the array is an object/dictionary with
    // a single key called "user"
    for (NSDictionary *element in results) {
        // 3. the value of the "user" key is itself another object/dictionary
        // with various key-value pairs
        NSDictionary *user = [element objectForKey:@"user"];
        NSString *title = [user objectForKey:@"NAME"];
        NSLog(@"%@", title);
    }
    
    0 讨论(0)
提交回复
热议问题