Search code examples
objective-cjsonnsstringnsdatanslog

How to NSLog NSData JSON response in JSON format?


Is there a way I can NSLog JSON response of NSData in JSONformat?

NSLog(@"JSON NSString: %@" ,jsonData);

In this post they are printing NSDictionary,I can convert it to NSDictionary. and this solution returns (null).

How can I NSLog in JSON format?


Solution

  • • What's wrong:
    jsonData (as you gave) IS NOT a hexData representing a JSON.

    • Quick hack (not viable solution!) to get your JSON to use in your site CodeBeautify:

    NSDictionary *dictFromData = [NSKeyedUnarchiver unarchiveObjectWithData:jsonData];
    NSData *realJSONData = [NSJSONSerialization dataWithJSONObject:dictFromData options:0 error:nil];
    NSString *strFINAL = [[NSString alloc] initWithData:realJSONData encoding:NSUTF8StringEncoding];
    NSLog(@"StrFINAL: %@", strFINAL);
    

    Note: Yeah, I bypassed the error parameters, and we shouldn't. With NSJSONWritingPrettyPrinted instead of 0 in options: parameter, you have a result almost similar to the one of CodeBeautify.

    • How did I get there:
    Firt, I copy/paste your bump string of NSData with this answer. That way, I got jsonData as you got. Then, I tried simply what it should be given your informations:

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&errorJSON];
    

    Which didn't work giving the error:

    Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x17598540 {NSDebugDescription=Invalid value around character 0.}

    But with NSDictionary *dictWithData = [NSKeyedUnarchiver unarchiveObjectWithData:jsonData];, I managed to get the real NSDictionary. But NSKeyedArchiver/NSKeyedUnarchiver are doing something "equivalent" to NSJSONSerialization: it serializes, transforming a NSObject into NSData (and vice-versa). But more powerful: for any kind of object that are NSCoding compliant. Here, since it's originally from a JSON (only NSString, NSNumber, NSArray and NSDictionary objects, and not a custom one), it's working without any more code. Did you for instance tried to save it into NSUserDefaults and it's not a .plist either (that was also one on my tries, I saved jsonData into memory, and used dictionaryWithContentsOfFile: giving me weird answer, but a important one in the bump of it: ""$class" = "{value = 23}";" which lead me to NSKeyArchiver/NSKeyUnarchiver). I don't know what you did exactly.

    • Conclusion:
    So clearly, somewhere, you mixed stuff found on the web. You need to rework that. You can't let it like this. There is issue in your code elsewhere. Where did you get jsonData from? What did you do with it?