parsing NSJSONReadingAllowFragments

前端 未结 2 643
北恋
北恋 2020-12-21 02:06

I am receiving some json data in my app:

NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonResponse options:NSJSONReadingAllowFragments         


        
相关标签:
2条回答
  • 2020-12-21 02:43

    It seems that your server sends "nested JSON": jsonResponse is a JSON string (not a dictionary). The value of that string is again JSON data representing a dictionary.

    In that case you have to de-serialize the JSON twice:

    NSString *jsonString = [NSJSONSerialization JSONObjectWithData:jsonResponse options:NSJSONReadingAllowFragments error:nil];
    NSData *innerJson = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:innerJson options:0 error:nil];
    
    NSString *email = jsonDict[@"email"];
    
    0 讨论(0)
  • 2020-12-21 02:51

    the 'json' object is obviously not a dictionary hence the error.

    you are passing the NSJSONReadingAllowFragments flag to JSONObjectWithData:options:error: which says:

    Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.

    you need to check the class type of the object returned from the method.

    Additionally you are under the false impression that you would get a mutable instance from the method call. If you want a mutable instance to be returned you need to use NSJSONReadingMutableContainers for mutable arrays/dics or NSJSONReadingMutableLeaves for mutable strings

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