如何在Ios

时间:2017-03-25 08:01:50

标签: ios objective-c json http-post

我将JSON数据转换成以下格式,我如何将值发布到它中,因为它给了我错误:Domain:NSCocoaErrorDomain" Json Text没有以数组或对象和选项开头,以允许片段未设置!请帮忙!!!

[
 { "No:"1" , "firstname":dhruv ....},
 { "No:"2", "firstname" : something i want to post...} ]

代码:

Nsstring* URL string = [NStringwithformat:@Myurl?fname=%(value from editext ]

1 个答案:

答案 0 :(得分:1)

NSArray *arrData = @[@{
                          @"No": @"1",
                          @"firstname": @"dhruv"},
                        @{
                           @"No": @"2",
                           @"firstname": @"something i want to post"
                        }];

NSData *data = [NSJSONSerialization dataWithJSONObject:arrData options:0 error:nil];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"your url here"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest: request
                                                             fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                                 //Kindly use below either one  according to your response
                                                                 //If the response is in Dictionary format
                                                                 NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                                                 NSLog(@"%@", jsonDict);

                                                                 //If the response is in Array format
                                                                 NSArray *jsonArr = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                                                 NSLog(@"%@", jsonArr);
                                                             }];

[dataTask resume];