字符串,数组,json,字典之间的相互转化1
2017-07-12 本文已影响10人
f2efa87f6528
将NSData转化为NSString
+ (NSString *)jsonDataToString:(NSData *)jsonData
{
NSString *jsonString = @"";
if(jsonData != nil)
{
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
return jsonString;
}
将字典或者数组转化为JSON Data
+ (NSData *)toJSONData:(id)theData
{
NSError *error = nil;
NSData *jsonData = nil;
if ([NSJSONSerialization isValidJSONObject:theData]) {
jsonData = [NSJSONSerialization dataWithJSONObject:theData
options:NSJSONWritingPrettyPrinted
error:&error];
}
if ([jsonData length] > 0 && error == nil){
return jsonData;
} else {
return nil;
}
}
将Data转化为jSON
+ (id)jsonDataToObj:(NSData *)data
{
id obj = nil;
if (data) {
obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
}
return obj;
}
#pragma mark - json String to Object
+ (id)jsonStringToObj:(NSString *)jsonString
{
id obj = nil;
if (jsonString) {
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
if (data) {
obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
}
}
return obj;
}
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
if (jsonString && [jsonString isKindOfClass:[NSDictionary class]])
{
return [(NSDictionary*)jsonString copy];
}
else if (jsonString && [jsonString isKindOfClass:[NSString class]] && jsonString.length > 0)
{
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
return [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
}
else
{
return nil;
}
}
+ (NSArray *)arrayWithJsonString:(NSString *)jsonString
{
if (jsonString == nil || ![jsonString isKindOfClass:[NSString class]] || jsonString.length <= 0) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
return nil;
}
return arr;
}