在JSON中如何让数组正常显示

我要在JSON中发送数组

代码如下:

-(void)getConnection {

    NSArray *comment=[NSArray arrayWithObjects:@"aaa",@"bbb",@"ccc",@"hello,yes,tell", nil];

    NSURL *aurl=[NSURL URLWithString:@"http://sajalaya.com/taskblazer/staffend/form/iphonearraytest.php"];

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:aurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    [request setHTTPMethod:@"POST"];

   NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:comment options:NSJSONWritingPrettyPrinted error:nil];
   NSString *new = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];

 // NSString *new = [comment JSONString];

 // NSArray *new=[comment jsonvalue];

    NSString *postString=[NSString stringWithFormat:@"tag=&comment=%@&total=%@",new,@"4"];

    NSLog(@"this is post string%@",postString);
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

     [NSURLConnection connectionWithRequest:request delegate:self];       
}

ChatGPT尝试为您解答,仅供参考
在这段代码中,你想将一个NSArray对象转换为JSON格式并将其发送到服务器。


要将NSArray对象转换为JSON,你可以使用NSJSONSerialization类中的dataWithJSONObject:options:error:方法。该方法接受一个参数comment(你的NSArray对象)和一个可选的options参数,然后返回一个NSData对象,该对象包含序列化后的JSON数据。你可以使用initWithData:encoding:方法将此NSData对象转换回字符串,然后将其添加到您的HTTP请求体中。


示例代码如下:

NSArray *comment = [NSArray arrayWithObjects:@"aaa", @"bbb", @"ccc", @"hello,yes,tell", nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:comment options:0 error:&error];
if (!jsonData) {
    NSLog(@"Error serializing array to JSON: %@", error);
} else {
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *postString = [NSString stringWithFormat:@"tag=&comment=%@&total=%@", jsonString, @"4"];
    // set the HTTP body of your request to the serialized JSON string
}