3

Im trying to create a json array out of nsmutable array.

To do so, Im trying to convert nsmutable array to nsdata as follows,

 NSData *dataArray = [NSKeyedArchiver archivedDataWithRootObject:self.countryNameArray];

self.countryNameArray is a mutable array that contains names of countries.

Then Im trying to create a json array out of NSData as follows

NSString* jsonArray = [[NSString alloc] initWithBytes:[dataArray bytes] length:[dataArray length] encoding:NSUTF8StringEncoding];

but the problem is that, jsonArray is null when Im trying to use it.

2
  • Too many Possible result : google.co.in/… Commented May 30, 2016 at 13:11
  • I have tried them.... Commented May 30, 2016 at 13:14

3 Answers 3

7
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Sign up to request clarification or add additional context in comments.

Comments

5

Swift 3

do {
    let data = try JSONSerialization.data(withJSONObject: YOUR VARIABLE HERE)
    let dataString = String(data: data, encoding: .utf8)!
    print(dataString)
} catch {
    print("JSON serialization failed: ", error)
}

Comments

2

You are mixing up NSKeyedArchiver and JSON.

archivedDataWithRootObject: produces an NSArray in an unspecified format. You have no idea what the format is, except that you can re-create the NSArray later from that data with matching calls.

You then make the assumption that the NSData contains a string in UTF-8 format. There is absolutely no reason why that would be the case. And there is absolutely, totally no reason why creating an NSString would give you an NSArray!.

Look at the documentation of NSJSONSerializer. It's blatantly obvious from the documentation how you create a JSON object from an array or dictionary. And NSKeyedArchiver has absolutely nothing to do with it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.