Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

ios - How to send input in JSON form for nested values in NSDictionary

If the code for input a simple non-nested values is:

$values = array('input_values' => array('input_1'   => 'Testing',
                                        'input_2'   => 'Testing',
                                        'input_3'   => 'Testing',));

and in Obj-C it will go as:

 NSDictionary *params = @{@"input_1": @"Testing",
                             @"input_2": @"Testing",
                             @"input_3": @"Testing"};

    NSMutableDictionary *modify = [NSMutableDictionary new];
    [modify  setObject:params forKey:@"input_values"];

Then how do we convert and send this nested code in obj-C?

$forms = array(
       array(
         'title'          => 'API Generated 10',
         'description'    => 'This is the description',
         'labelPlacement' => 'top_label',
         'button'         => array(
                   'type' => 'text'
         ),
        'confirmations'   => array(
                   array(
                    'id' => 0,
                    'name' => 'Default Confirmation',
                    'type' => 'message',
                    'message' => 'Thanks for contacting us! We will get in touch with you shortly.',
                    'isDefault' => true,
                   ),
             ),
        'fields'          => array(
                   array(
                    'id' => '1',
                    'label' => 'My Text',
                    'type'  => 'text'
                   )
                   array(
                    'id' => '2',
                    'label' => 'My Text 2',
                    'type'  => 'text'
                   )
            ,
      ),
    );


UPDATE: Based on the answers below if I implement this:

// Initially Crate one Main Dictionary for Save
    NSMutableDictionary *modify = [NSMutableDictionary new];
    NSMutableArray *ParamArray = [NSMutableArray array];

    NSDictionary *type = @{@"type": @"type" };

    NSDictionary *original = @{@"title": @"API Generated 10",
                               @"description": @"This is the description for the form generated by the API",
                               @"labelPlacement": @"top_label",
                               @"button":type
                               };

    // NSArray * svalues = original.mutableCopy;
    modify = original.mutableCopy;



    // store all Fields in one array
    NSDictionary *fieldsparams = @{@"id": @"1",
                                   @"label": @"My Text",
                                   @"type": @"text"};
    NSArray * fieldsvalues = fieldsparams.mutableCopy;
    [modify setObject:fieldsvalues forKey:@"fields"];

    NSDictionary *confirmationssparams = @{@"id": @"0",
                                           @"name": @"Default Confirmation",
                                           @"type": @"message",
                                           @"message":@"Thanks for contacting us! We will get in touch with you shortly.",
                                           @"isDefault":@YES
                                           };
    NSArray * confirmationsvalues = confirmationssparams.mutableCopy;
    [modify setObject:confirmationsvalues forKey:@"confirmations"];


    [ParamArray addObject:modify];

    NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    //1
    AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    [manager POST:escapedPath parameters:modify progress:nil success:^(NSURLSessionTask *task, id responseObject)
     {
         NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
         NSLog(@"json == %@",json);

     }failure:^(NSURLSessionTask *operation, NSError *error)
     {
         NSLog(@"%@",[error localizedDescription]);
     }];

It still gave me 400 Bad request. As based on previous experience I need NSMutableDictionary of the above data in order to send it as JSON Object in parameters of AFNetworking. If I pass it NSMutableArray it doesn't work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try below code:

    NSArray *fieldsArr =  //your fieldsArr
    NSArray *confirmationsArr = //your confirmationsArr
    NSArray *buttonArr = //your buttonArr

    NSMutableDictionary *modify = [NSMutableDictionary new];
    [modify  setValue:@"Titlr" forKey:@"title"];
    [modify  setValue:@"Disciption" forKey:@"description"];
    [modify  setValue:@"lablPlacement" forKey:@"labelPlacement"];
    [modify  setObject:buttonArr forKey:@"button"];
    [modify  setObject:fieldsArr forKey:@"fields"];
    [modify  setObject:confirmationsArr forKey:@"confirmations"];

    NSMutableArray *mainArr = [NSMutableArray new];

    [mainArr addObject:modify];

//Make request

NSError *error;

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
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"];

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


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

}];

[postDataTask resume];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...