【问题标题】:How to add the JSON data to NSARRAY?如何将 JSON 数据添加到 NSARRAY?
【发布时间】:2016-04-13 12:56:41
【问题描述】:
[{"name":"Mocha","latitude":17.418694 , "longitude":78.445116},
 {"name":"Rock Castle","latitude":17.420865 , "longitude":78.442219},
{"name":"RnB Select","latitude":17.420639 , "longitude":78.443635}
]
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations{
   location=locations.lastObject;
    [[self latitudeValue] setText:[NSString stringWithFormat:@"%.6f",location.coordinate.latitude]];
    [[self longnitudeValue] setText:[NSString stringWithFormat:@"%.6f",location.coordinate.longitude]];
//    [[self altitudeValue] setText:[NSString stringWithFormat:@"%.2f feet",location.altitude*METERS_FEET]];
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 2*METERS_MILE, 2*METERS_MILE);
    [[self mapView] setRegion:viewRegion animated:YES];
     NSArray *arr = [[NSUserDefaults standardUserDefaults] objectForKey:@"myStoredObject"];
    NSDictionary *zeroth=arr[0];
    NSLog(@"oth position,,,,%@",zeroth);
    NSDictionary *firstPosition = arr[1];
    NSLog(@"first position is .....%@",firstPosition);
    NSDictionary *secondPosition = arr[2];
    NSLog(@"second position is .....%@",secondPosition);


    MKPointAnnotation *point2 = [[MKPointAnnotation alloc] init];

    point2.coordinate =CLLocationCoordinate2DMake([[firstPosition valueForKey:@"latitude"] doubleValue], [[firstPosition valueForKey:@"longitude"] doubleValue]);
    point2.title =[firstPosition valueForKey:@"name"];
[self.mapView addAnnotation:point2];
    MKPointAnnotation *point3 = [[MKPointAnnotation alloc] init];
    point3.coordinate = CLLocationCoordinate2DMake([[firstPosition valueForKey:@"latitude"] doubleValue], [[firstPosition valueForKey:@"longitude"] doubleValue]);
    point3.title =[firstPosition valueForKey:@"name"];
    [self.mapView addAnnotation:point3];

    MKPointAnnotation *point4 = [[MKPointAnnotation alloc] init];
    point4.coordinate = CLLocationCoordinate2DMake([[secondPosition valueForKey:@"latitude"] doubleValue], [[secondPosition valueForKey:@"longitude"] doubleValue]);
    point4.title =[secondPosition valueForKey:@"name"];
    [self.mapView addAnnotation:point4];

MKCircle *circleoverlay = [MKCircle circleWithCenterCoordinate:_mapView.userLocation.coordinate radius:1000];
    [circleoverlay setTitle:@"Circle"];
    [_mapView addOverlay:circleoverlay];
    NSLog(@"circle is drawn");




}

以上代码显示了 Json 数据... 这是我通过编写以下代码从 URL 获取的 JSON 数据

 NSMutableURLRequest *tRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.ctrlm.in/kvikdata/locations.json"]];
        NSLog(@"url is %@",tRequest);
        [tRequest setHTTPMethod:@"GET"];
        [tRequest setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection
     sendAsynchronousRequest:tRequest
     queue:queue
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error) {
         if ([data length] >0 && error == nil){
             dispatch_async(dispatch_get_main_queue(), ^{
                 NSError *error;
                 id jsonObject = [NSJSONSerialization
                                  JSONObjectWithData:data
                                  options:NSJSONReadingAllowFragments
                                  error:&error];
                 NSLog(@"Successfully deserialized.2222222..%@",jsonObject);

NSArray *myArr = [jsonObject 副本]; // 这里 myArr = yourData 来自您的响应。我拿它 nil 来演示 NSLog(@"我的数组是 %@",myArr);

       NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];

         [myDefaults setObject:myArr forKey:@"myStoredObject"]; // by this you can store object

                 if (jsonObject != nil && error == nil){   
                     NSLog(@"Successfully deserialized...%@",jsonObject);
                 }
             });
         }
     }];

通过写入 NSUserDefaults,第一个数据会根据 json 对象进行更新。再次,当我将位置名称从 @"mocha" 更改为 @"test1" 时,它没有更新...为什么? 谢谢你

【问题讨论】:

  • 你发布的json数据看起来像一个数组。
  • 您能否正确缩进并清理您的代码?它或多或少不可读。还要保持一致,放置空格的位置和不放置空格的位置!

标签: objective-c json nsurlrequest


【解决方案1】:

你得到的对象已经是数组。只需使用NSArray * jsonObject 而不是id jsonObjectClick here tutsplus 教程。 Raywenderlich 也是另一个答案中提到的不错的选择。

您应该使用AFNetworking 来调用网络服务。 AFNetworking - Github

希望这会对您有所帮助。 :)

根据评论中的问题更新:

您应该使用本地数据库来存储您从服务器获取的任何字典或数组。如果数据太多,数据之间关系复杂,可以使用sqlitecore data。如果您是简单数据(如您的问题所示),您可以使用NSUserDefaults,如下例所示,

 NSArray *myArr = nil; // here myArr = yourData from your response. i take it nil for demonstrate

NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];

[myDefaults setObject:myArr forKey:@"myStoredObject"]; // by this you can store object


NSArray *arr = [myDefaults objectForKey:@"myStoredObject"]; // like this you can retrivie object

现在您可以使用 arr 在地图上显示注释。每当您从服务器调用 [myDefaults setObject:myArr forKey:@"myStoredObject"]; 获得响应时,myArr 应该是新的响应。所以它会用新的覆盖你的旧数据。希望这会有所帮助。 :)

【讨论】:

  • 我通过编写上面的代码从url获取json数据......我使用MKPointAnnotation编写上述三个地址的代码......如下所示
  • 是的,没有必要,但如果有人不太熟悉这个概念,那么afnetworking 可以让他们的任务变得简单一些。 :)
  • @nandini,你想说什么?没有得到你的评论! kike 下面是指哪里?
  • 我通过编写上面的代码从url获取json数据。我使用MKPointAnnotation编写上述三个地址的代码..如下面MKPointAnnotation *point2 = [[MKPointAnnotation alloc] init]; point2.coordinate = CLLocationCoordinate2DMake(17.418694, 78.445116); point2.title = @"摩卡"; [self.mapView addAnnotation:point2];我写的和剩下的两个地址一样……它是静态的……我的问题是,如果他们改变 jsondata 中的值,它应该在我的代码中动态改变……我应该如何编写代码?我应该将json数据存储在字典中吗?谢谢你
  • 嘿,@nandini 我已根据您的问题更新了我的答案。看看这个。 :)
【解决方案2】:

你已经得到数组,使用NSArray insted of id 然后你会得到数组中的响应

NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error:& error];

建议

NSURLConnection 在 ios 9 中已弃用,因此请使用 NSURLSession

这可能对你有帮助

https://www.objc.io/issues/5-ios7/from-nsurlconnection-to-nsurlsession/ https://www.raywenderlich.com/110458/nsurlsession-tutorial-getting-started

【讨论】:

  • 将其保存到 id 变量中,而不是 NSArray
  • @trojanfoe :是的,她只需要数组中的响应 :)
  • @Lion,它对我非常有用,而且价值观正在动态变化。谢谢你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-15
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多