iOS 初步判断string是不是jsonstring
2019-11-11 本文已影响0人
风___________
初步判断string是不是json格式
+ (BOOL)isJsonString:(NSString *)jsonString{
if (jsonString.length < 2) return NO;
if (!([jsonString hasPrefix:@"{"] || [jsonString hasPrefix:@"["])) return NO;
// {:123 }:125 [: 91 ]:93
return [jsonString characterAtIndex:jsonString.length-1]-[jsonString characterAtIndex:0] == 2;
}
jsonToObj
+ (id)jsonToObj:(NSString *)jsonString{
if (![self isJsonString:jsonString]) return nil;
NSError *err;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id obj;
if (jsonData) {
obj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
}
if (err) {
return nil;
}
return obj;
}