user826955
user826955

Reputation: 3206

NSJSONSerialization creates garbage

I have some problems with creating a NSString-representation (JSON-string) of a NSDictionary using NSJSONSerialization. I have used JSONKit before, but since its kind of deprecated in iOS9 (and crashes), I switched to NSJSONSerialization.

This is my code:

// `userSettings` will be of type NSMutableDictionary*

NSData* data= [NSJSONSerialization dataWithJSONObject:userSettings options:0 error:&error];
NSString* settingsString= [NSString stringWithUTF8String:data.bytes];

currentUser.settings= settingsString;   // NSString* property

Now, from time to time, this code works, but then sometimes the settingsString will be nil. And when I inspect the data object in the debugger, the bytes property shows the JSON-String followed by some random garbage, like this:

1 = 0x00007ff1ba814000 "{\"residua
...
lculatePlanned\":\"0\",\"wizardUserId\":\"\"}UITextColor\x91UISystemColorName\x94UIBaselineAdjustment\x8cUISystemFont\x89NS.intval\x8eUIShadowOffset\x94UIAutoresizeSubviews\x8dUIContentMode\x85NSRGB\x8aUIFontName\x8bUITextLabel\x8eNSInlinedValue\x91UIDetailTextLabel\x99UIUserInteractionDisabled\x9dUITableCellBackgroundColorSet\x94UINibEncoderEmptyKey\x87NSWhite\x8cNSColorSpace\x8fUITextAlignment\xa3UINibAccessibilityConfigurationsKey\x92UIAutoresizingMask\x99UIProxiedObjectIdentifier\x87UIAlpha\x87UIWhite\x9aUIFontDescriptorAttributes\x8cUIFontTraits\x86NSSize\x95UIColorComponentCount\x91UIMinimumFontSize\x86UIText\x96UIMultipleTouchEnabled\x8dUIDestination\x94UIMi..."
                                             ^ start of garbage after end of dictionary

What am I doing wrong?

Upvotes: 0

Views: 285

Answers (1)

zaph
zaph

Reputation: 112857

Do not use + stringWithUTF8String:, it relies on a A NULL-terminated C array of bytes and there is only a NULL terminator by chance and it may be well after the end of the charactery you expect.

Instead use:

- (instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding

Ex:

NSString *settingsString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

Upvotes: 3

Related Questions