How to convert JSON serialized data to NSDictionary

前端 未结 5 563
小鲜肉
小鲜肉 2020-12-02 14:28

I have used this method,

NSDictionary *jsonObject=[NSJSONSerialization 
       JSONObjectWithData:jsonData 
                  options:NSJSONReadingMutableLea         


        
相关标签:
5条回答
  • 2020-12-02 14:37
    NSError* error;
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    

    This is just a more succinct version of the top post.

    0 讨论(0)
  • 2020-12-02 14:42

    Check your json input, could it be that your root element is neither a dictionary nor an array? The documentation says you have to specify NSJSONReadingAllowFragments as the option in this case.

    #import <Foundation/Foundation.h>
    
    int main(int argc, char *argv[]) {
        NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];
    
        NSData *jsonData = [@"{ \"key1\": \"value1\" }" dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *jsonObject=[NSJSONSerialization 
               JSONObjectWithData:jsonData 
                          options:NSJSONReadingMutableLeaves 
                            error:nil];
        NSLog(@"jsonObject is %@",jsonObject);
    
        [p release];
    }
    

    Output:

    2012-09-26 16:06:51.610 Untitled[19164:707] jsonObject is {
        key1 = value1;
    }
    
    0 讨论(0)
  • 2020-12-02 14:43

    Please Try the following Code.

    NSError* error;
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                         options:kNilOptions 
                                                           error:&error];
    
    NSArray* latestLoans = [json objectForKey:@"loans"];
    
    NSLog(@"loans: %@", latestLoans);
    
    0 讨论(0)
  • 2020-12-02 14:51

    Just in case anyone is here to see swift code:

    NSData to NSDictionary

    let dictionary:NSDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(jsonData)! as NSDictionary
    

    NSData to NSString

    let resstr = NSString(data: res, encoding: NSUTF8StringEncoding)
    
    0 讨论(0)
  • let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

    0 讨论(0)
提交回复
热议问题