JSONparsing在iOS 7中

我正在创build一个作为现有网站的应用程序。 他们目前拥有以下格式的JSON:

[ { "id": "value", "array": "[{\"id\" : \"value\"} , {\"id\" : \"value\"}]" }, { "id": "value", "array": "[{\"id\" : \"value\"},{\"id\" : \"value\"}]" } ] 

他们使用Javascript转义\字符后parsing。

我的问题是当我使用下面的命令在iOS中parsing它:

 NSArray *result = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&localError]; 

并做到这一点:

 NSArray *Array = [result valueForKey:@"array"]; 

我得到了NSMutableString对象而不是一个Array

  • 该网站已经在生产,所以我不能让他们改变他们现有的结构,以返回一个适当的JSON对象。 对他们来说这将是很多工作。

  • 所以,直到他们改变底层的结构,有什么办法可以使它在iOS工作,就像他们在他们的website上使用javascript一样?

任何帮助/build议对我都很有帮助。

正确的JSON应该看起来像这样:

 [ { "id": "value", "array": [{"id": "value"},{"id": "value"}] }, { "id": "value", "array": [{"id": "value"},{"id": "value"}] } ] 

但是,如果你被困在你的问题提供的格式,你需要使NSJSONReadingMutableContainers字典可变,然后再次调用NSJSONSerialization每个array条目:

 NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; if (error) NSLog(@"JSONObjectWithData error: %@", error); for (NSMutableDictionary *dictionary in array) { NSString *arrayString = dictionary[@"array"]; if (arrayString) { NSData *data = [arrayString dataUsingEncoding:NSUTF8StringEncoding]; NSError *error = nil; dictionary[@"array"] = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (error) NSLog(@"JSONObjectWithData for array error: %@", error); } } 

试试这个简单的方法….

 - (void)simpleJsonParsing { //-- Make URL request with server NSHTTPURLResponse *response = nil; NSString *jsonUrlString = [NSString stringWithFormat:@"http://domain/url_link"]; NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; //-- Get request and response though URL NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url]; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; //-- JSON Parsing NSMutableArray *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]; NSLog(@"Result = %@",result); for (NSMutableDictionary *dic in result) { NSString *string = dic[@"array"]; if (string) { NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; dic[@"array"] = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; } else { NSLog(@"Error in url response"); } } } 

正如上面所说的,你必须先使用NSJSONSerializationJSON反序列化为可用的数据结构,如NSDictionaryNSArray

但是,如果要将JSON的内容映射到Objective-C对象,则必须将NSDictionary/NSArray每个属性映射到对象属性。 如果你的对象有很多属性,这可能会有点痛苦。

为了使这个过程自动化,我build议你在NSObject (一个个人项目)上使用Motis类来完成它,因此它非常轻便和灵活。 你可以阅读如何使用它在这个职位 。 但只是为了向您展示,您只需要定义一个字典,将JSON对象属性映射到NSObject子类中的Objective-C对象属性名称:

 - (NSDictionary*)mjz_motisMapping { return @{@"json_attribute_key_1" : @"class_property_name_1", @"json_attribute_key_2" : @"class_property_name_2", ... @"json_attribute_key_N" : @"class_property_name_N", }; } 

然后通过执行parsing:

 - (void)parseTest { // Some JSON object NSDictionary *jsonObject = [...]; // Creating an instance of your class MyClass instance = [[MyClass alloc] init]; // Parsing and setting the values of the JSON object [instance mjz_setValuesForKeysWithDictionary:jsonObject]; } 

字典中属性的设置是通过KeyValueCoding (KVC)完成的,您可以在通过KVCvalidation进行设置之前validation每个属性。

希望它可以帮助你尽可能地帮助我。

 //-------------- get data url-------- NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://echo.jsontest.com/key/value"]]; NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSLog(@"response==%@",response); NSLog(@"error==%@",Error); NSError *error; id jsonobject=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; if ([jsonobject isKindOfClass:[NSDictionary class]]) { NSDictionary *dict=(NSDictionary *)jsonobject; NSLog(@"dict==%@",dict); } else { NSArray *array=(NSArray *)jsonobject; NSLog(@"array==%@",array); } 

// —————– json for localfile —————————

 NSString *pathofjson = [[NSBundle mainBundle]pathForResource:@"test1" ofType:@"json"]; NSData *dataforjson = [[NSData alloc]initWithContentsOfFile:pathofjson]; arrayforjson = [NSJSONSerialization JSONObjectWithData:dataforjson options:NSJSONReadingMutableContainers error:nil]; [tableview reloadData]; 

// ————- json for urlfile ——————————– —

 NSString *urlstrng = @"http://www.json-generator.com/api/json/get/ctILPMfuPS?indent=4"; NSURL *urlname = [NSURL URLWithString:urlstrng]; NSURLRequest *rqsturl = [NSURLRequest requestWithURL:urlname]; 

// ———— json for urlfileasynchronous———————-

 [NSURLConnection sendAsynchronousRequest:rqsturl queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { arrayforjson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; [tableview reloadData]; }]; 

// ————- json for urlfile通过同步———————-

 NSError *error; NSData *data = [NSURLConnection sendSynchronousRequest:rqsturl returningResponse:nil error:&error]; arrayforjson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; [tableview reloadData]; } ; 
  • 在将它传递给NSJSONSerialization之前,您可能总是使用NSJSONSerialization 。 或者你可以使用string来构造另一个json object来获取array

  • NSJSONSerialization是正确的,你的例子中的值应该是一个string。

正如另一个答案所说,这个价值是一个string。

你可以通过将该string转换为数据来避开它,因为它似乎是一个有效的jsonstring,然后将该json数据对象parsing回数组中,您可以将该数组添加到字典中作为键的值。

  NSError *err; NSURL *url=[NSURL URLWithString:@"your url"]; NSURLRequest *req=[NSURLRequest requestWithURL:url]; NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:&err]; NSDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; NSArray * serverData=[[NSArray alloc]init]; serverData=[json valueForKeyPath:@"result"]; 
 NSString *post=[[NSString stringWithFormat:@"command=%@&username=%@&password=%@",@"login",@"username",@"password"]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.blablabla.com"]]; [request setHTTPMethod:@"POST"]; [request setValue:@"x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; [request setHTTPBody:[NSData dataWithBytes:[post UTF8String] length:strlen([post UTF8String])]]; NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; id jsonobject=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; if ([jsonobject isKindOfClass:[NSDictionary class]]) { NSDictionary *dict=(NSDictionary *)jsonobject; NSLog(@"dict==%@",dict); } else { NSArray *array=(NSArray *)jsonobject; NSLog(@"array==%@",array); } 

可能这会帮助你。

 - (void)jsonMethod { NSMutableArray *idArray = [[NSMutableArray alloc]init]; NSMutableArray *nameArray = [[NSMutableArray alloc]init]; NSMutableArray* descriptionArray = [[NSMutableArray alloc]init]; NSHTTPURLResponse *response = nil; NSString *jsonUrlString = [NSString stringWithFormat:@"Enter your URL"]; NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url]; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]; NSLog(@"Result = %@",result); for (NSDictionary *dic in [result valueForKey:@"date"]) { [idArray addObject:[dic valueForKey:@"key"]]; [nameArray addObject:[dic valueForKey:@"key"]]; [descriptionArray addObject:[dic valueForKey:@"key"]]; } } 

JSON默认方法:

 + (NSDictionary *)stringWithUrl:(NSURL *)url postData:(NSData *)postData httpMethod:(NSString *)method { NSDictionary *returnResponse=[[NSDictionary alloc]init]; @try { NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:180]; [urlRequest setHTTPMethod:method]; if(postData != nil) { [urlRequest setHTTPBody:postData]; } [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [urlRequest setValue:@"text/html" forHTTPHeaderField:@"Accept"]; NSData *urlData; NSURLResponse *response; NSError *error; urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error]; returnResponse = [NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error]; } @catch (NSException *exception) { returnResponse=nil; } @finally { return returnResponse; } } 

返回方法:

 +(NSDictionary *)methodName:(NSString*)string{ NSDictionary *returnResponse; NSData *postData = [NSData dataWithBytes:[string UTF8String] length:[string length]]; NSString *urlString = @"https//:..url...."; returnResponse=[self stringWithUrl:[NSURL URLWithString:urlString] postData:postData httpMethod:@"POST"]; return returnResponse; } 

@property NSMutableURLRequest * urlReq;

@property NSURLSession * session;

@property NSURLSessionDataTask * dataTask;

@property NSURLSessionConfiguration * sessionConfig;

@property NSMutableDictionary * appData;

@property NSMutableArray * valueArray; @属性NSMutableArray * keysArray;

  • (void)viewDidLoad {[super viewDidLoad]; self.valueArray = [[NSMutableArray alloc] init]; self.keysArray = [[NSMutableArray alloc] init]; self.linkString = @“ http://country.io/names.json ”; [self getData];

– (无效)的getData
{self.urlReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.linkString]];

 self.sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; self.session = [NSURLSession sessionWithConfiguration:self.sessionConfig]; self.dataTask = [self.session dataTaskWithRequest:self.urlReq completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { self.appData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"%@",self.appData); self.valueArray=[self.appData allValues]; self.keysArray = [self.appData allKeys]; }]; [self.dataTask resume]; 
 #define FAVORITE_BIKE @"user_id=%@&bike_id=%@" @define FAVORITE_BIKE @"{\"user_id\":\"%@\",\"bike_id\":\"%@\"}" NSString *urlString = [NSString stringWithFormat:@"url here"]; NSString *jsonString = [NSString stringWithFormat:FAVORITE_BIKE,user_id,_idStr]; NSData *myJSONData =[jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSMutableData *body = [NSMutableData data]; [body appendData:[NSData dataWithData:myJSONData]]; [request setHTTPBody:body]; NSError *error; NSURLResponse *response; NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSString *str = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; if(str.length > 0) { NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding]; NSMutableDictionary *resDict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; } 
 -(void)responsedata { NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:replacedstring]]; [request setHTTPMethod:@"GET"]; NSURLSessionConfiguration *config=[NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session=[NSURLSession sessionWithConfiguration:config]; NSURLSessionDataTask *datatask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error) { NSLog(@"ERROR OCCURE:%@",error.description); } else { NSError *error; NSMutableDictionary *responseDict=[[NSMutableDictionary alloc]init]; responseDict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error]; if (error==nil) { // use your own array or dict for fetching as per your key.. _responseArray =[[NSMutableArray alloc]init]; _geometryArray=[[NSMutableArray alloc]init]; _responseArray=[responseDict valueForKeyPath:@"result"]; referncestring =[[_photosArray objectAtIndex:0]valueForKey:@"photo_reference"]; _geometryArray=[_responseArray valueForKey:@"geometry"]; // _locationArray=[[_geometryArray objectAtIndex:0]valueForKey:@"location"]; _locationArray=[_geometryArray valueForKey:@"location"]; latstring=[_locationArray valueForKey:@"lat"]; lngstring=[_locationArray valueForKey:@"lng"]; coordinates = [NSMutableString stringWithFormat:@"%@,%@",latstring,lngstring]; } } dispatch_sync(dispatch_get_main_queue(), ^ { // call the required method here.. }); }]; [datatask resume]; //dont forget it }