user6092898
user6092898

Reputation:

Converting NSMutableArray to JSONArray

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.

Upvotes: 3

Views: 2512

Answers (3)

Sathya Baman
Sathya Baman

Reputation: 3515

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)
}

Upvotes: 5

gnasher729
gnasher729

Reputation: 52530

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.

Upvotes: 2

Bhadresh Mulsaniya
Bhadresh Mulsaniya

Reputation: 2640

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Upvotes: 6

Related Questions