xinyoulingxi1_tong 2012-11-27 08:53 采纳率: 0%
浏览 1085

在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];       
}
  • 写回答

1条回答 默认 最新

  • ChatGPTᴼᴾᴱᴺᴬᴵ 2022-12-19 12:15
    关注

    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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题