gpt4 book ai didi

ios - 如何将NSStrings的NSArray转换成Json String iOS

转载 作者:可可西里 更新时间:2023-11-01 06:20:07 29 4
gpt4 key购买 nike

我有一个卷号数组

NSArray *rollArray = [NSArray arrayWithObjects:@"1", @"22", @"24", @"11", nil];

我需要在 Web 服务请求中发送这个数组

格式是这样的(JSON格式)

JSON 数据

{
"existingRoll":["22","34","45","56"], // Array of roll numbers
"deletedRoll":["20","34","44","56"] // Array of roll numbers
}

但我在将卷数数组 (rollArray) 转换为 json 字符串时遇到问题以所需的格式。

我正在尝试这个

 NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setValue:[rollArray componentsJoinedByString:@","] forKey:@"existingRoll"];

NSString *str = [Self convertToJSONString:postDict]; // converts to json string

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str options:0 error:nil];

[request setHTTPBody:jsonData];

我正在使用 iOS 7

最佳答案

无需使用以下代码片段:

  1. [rollArray componentsJoinedByString:@","]
  2. NSString *str = [Self convertToJSONString:postDict];

您可以使用以下代码创建 JSON:

NSArray *rollArray = [NSArray arrayWithObjects:@"1", @"22", @"24", @"11", nil];
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setValue:rollArray forKey:@"existingRoll"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];

// Checking the format
NSLog(@"%@",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);

关于ios - 如何将NSStrings的NSArray转换成Json String iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22635742/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com