如何创建嵌套的json对象

时间:2015-11-09 19:35:32

标签: objective-c ruby-on-rails json

"drive"=>{"admins_attributes"=>{"0"=>{"latitude"=>"42.2349343", "longitude"=>"-71.1133432"}, "1"=>{"latitude"=>"42.2349343", "longitude"=>"-71.1133432"}}}

我试图在目标c中收集一堆纬度和经度并将它们保存到rails后端并使用嵌套属性,但我无法弄清楚如何在目标c中形成这样的对象。每个纬度和经度都有自己的索引。

NSDictionary *position = [[NSDictionary alloc] initWithObjectsAndKeys:
                                      latitude, @"latitude",
                                      longitude, @"longitude",
                                      city, @"city",
                                      state, @"state",
                                      zipcode, @"zipcode",
                                      carrName, @"carrier",
                                      [NSNumber numberWithInt:signalStrength], @"signalStrength",
                                      signalType, @"signalType",nil];


 NSArray *positionArray = [NSArray arrayWithObjects:position, nil];

 [positions addObject:positionArray];

  NSError *error;

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:@"http://localhost:3001/api/v1/drives"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];

    NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:positions, @"positions_attributes", nil];

    NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
    [request setHTTPBody:postData];

    NSLog(@"JSON = %@", [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]);


    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                             options:kNilOptions
                                                               error:&error];
    }];

    [postDataTask resume];

0 个答案:

没有答案