与NSArray互转,下面方法只需将NSDictionary替换成NSArray
1.JSON to NSDictionary
- (NSDictionary *)dictionaryWithJson:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
return nil;
}
return dic;
}
2.NSDictionary to JSON
- (NSString*)jsonWithDictionary:(NSDictionary *)dic
{
NSString *jsonString = nil;
if ([NSJSONSerialization isValidJSONObject:dic])
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
jsonString =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (error) {
NSLog(@"Error:%@" , error);
}
}
return jsonString;
}