如何在ios中发布Json字符串

时间:2014-03-18 10:01:28

标签: ios iphone json ios7

发布“未将对象引用设置为对象实例”时出现错误。请帮帮我。

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:infoDictionary
                                                       options:NSJSONWritingPrettyPrinted error:&error];


    NSString *postString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];


    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://My url"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

    [request setHTTPBody:postData];
    NSURLResponse *response;
    NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
    NSLog(@"Reply: %@", theReply);

2 个答案:

答案 0 :(得分:0)

您没有在要传递的JSON中设置任何参数名称。

    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:infoDictionary options:NSJSONWritingPrettyPrinted error:&error];


                NSString *saveString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *postString = [NSString stringWithFormat:@"&YOUR_PARAMETER_NAME=%@",saveString];
                NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
                NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];


                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
                [request setURL:[NSURL URLWithString:@"http://My url"]];
                [request setHTTPMethod:@"POST"];
                [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
                [request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

                [request setHTTPBody:postData];
                NSURLResponse *response;
                NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
                NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
                NSLog(@"Reply: %@", theReply);

答案 1 :(得分:-1)

不要重新发明轮子。使用Restkit来完成这些工作。设置完成后,可以在一行代码中发布一个对象。