Reputation: 105
How to create json Object with NSData
in Objective C
. I'm having values in a NSData
variable.
Upvotes: 4
Views: 13446
Reputation: 4789
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"youur link"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
if([jsonObjects isKindOfClass:[NSArray class]]){
//Is array
}else if([jsonObjects isKindOfClass:[NSDictionary class]]){
//is dictionary
}else{
//is something else
}
EDIT FOR SWIFT
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>] {
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
Upvotes: 2
Reputation: 4212
You can use it like this in iOS 5 (if you are sure of your json structure you can directly use NSArray
or NSDictionary
doing a cast)
NSError *jsonError;
id jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:myData options:NULL error:&jsonError];
if(jsonError) {
// check the error description
NSLog(@"json error : %@", [jsonError localizedDescription]);
} else {
// use the jsonDictionaryOrArray
}
Upvotes: 6
Reputation: 20541
if you have a value in NSData object then you can convert it in NSString variable like bellow
NSString *response = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
Edited...
i am not sure what you want but i give you the json array from string like bellow..
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
NSArray *arrData = [json objectWithString:responseString error:&error];
[responseString release];
you can get data in array
hope this help you mate...
:)
Upvotes: 2