JSON Parsing in iOS 7

前端 未结 14 2241
长情又很酷
长情又很酷 2020-12-04 11:25

I am creating an app for as existing website. They currently has the JSON in the following format :

[

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


        
相关标签:
14条回答
  • 2020-12-04 11:59

    As people just said above, you must use the NSJSONSerialization to deserialise JSON into usable data structures as NSDictionary or NSArray first.

    However, if you want to map the content of your JSON to your Objective-C objects, you will have to map each attribute from the NSDictionary/NSArray to your object property. This might be a bit painful if your objects have many attributes.

    In order to automatise the process, I recommend you to use the Motis category on NSObject (a personal project) to accomplish it, thus it is very lightweight and flexible. You can read how to use it in this post. But just to show you, you just need to define a dictionary with the mapping of your JSON object attributes to your Objective-C object properties names in your NSObject subclasses:

    - (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",
                };
    }
    

    and then perform the parsing by doing:

    - (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];
    }
    

    The setting of the properties from the dictionary is done via KeyValueCoding (KVC) and you can validate each attribute before setting it via KVC validation.

    Hoping it helps you as much it helped me.

    0 讨论(0)
  • 2020-12-04 12:10

    May be this will help you.

    - (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"]];
    
        }
    
    }
    
    0 讨论(0)
  • 2020-12-04 12:11

    @property NSMutableURLRequest * urlReq;

    @property NSURLSession * session;

    @property NSURLSessionDataTask * dataTask;

    @property NSURLSessionConfiguration * sessionConfig;

    @property NSMutableDictionary * appData;

    @property NSMutableArray * valueArray; @property 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];

    -(void)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];
    
    0 讨论(0)
  • 2020-12-04 12:12

    // ----------------- 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 urlfile by asynchronous----------------------

    [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 by synchronous----------------------

    NSError *error;
    NSData *data = [NSURLConnection sendSynchronousRequest:rqsturl returningResponse:nil error:&error];
    
     arrayforjson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    
    [tableview reloadData];
    } ;
    
    0 讨论(0)
  • 2020-12-04 12:15
     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"];
    
    0 讨论(0)
  • 2020-12-04 12:15
    -(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
    
        }
    
    0 讨论(0)
提交回复
热议问题