我有一个滚动数字数组
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 String时遇到问题 以所需的格式。
我正在尝试这个
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
答案 0 :(得分:10)
无需使用以下代码段:
[rollArray componentsJoinedByString:@","]
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]);
答案 1 :(得分:2)
试试这个:
NSDictionary *object = @{
@"existingRoll":@[@"22",@"34",@"45",@"56"],
@"deletedRoll":@[@"20",@"34",@"44",@"56"]
};
if ([NSJSONSerialization isValidJSONObject:object]) {
NSData* data = [ NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:nil ];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(str);
}
答案 2 :(得分:0)
NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];
[postDict setValue:@"Login" forKey:@"methodName"];
[postDict setValue:@"admin" forKey:@"username"];
[postDict setValue:@"12345" forKey:@"password"];
[postDict setValue:@"mobile" forKey:@"clientType"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSString *urlString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [[NSString alloc] initWithFormat:@"jsonRequest=%@", urlString];
//@"jsonRequest={\"methodName\":\"Login\",\"username\":\"admin\",\"password\":\"12345\",\"clientType\":\"web\"}";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
答案 3 :(得分:0)
您可以使用以下方法从任何类型的NSArray获取Json字符串:
NSArray *rollArray = [NSArray arrayWithObjects:@"1", @"22", @"24", @"11", nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:rollArray options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Json string is: %@", jsonString);