根据您从 textFields 获取的所有值创建一个字典。它看起来像这样,
NSDictionary *dictionary = @{@"trailer":@{@"window":@"broken", @"sidesteps":@"missing", @"tractor": @{@"window":@"broken",@"sidesteps":@"missing"}, @"tire":@{@"tire1" : @{@"pressure" : @"120", @"rim":@"good"}}}};
输出:
dictionary = {
"trailer": {
"window": "broken",
"sidesteps": "missing",
"tractor": {
"window": "broken",
"sidesteps": "missing"
},
"tire": {
"tire1": {
"pressure": "120",
"rim": "good"
}
}
}
}
您可以使用NSMutableDictionary
动态创建类似的结构。您可以创建多个可变字典并将其添加为另一个字典的对象以实现上述结果。
要转换为 JSON 数据,您可以这样做,
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
如果要转换成字符串来查看数据,
NSString *jsonString = [[NSString alloc] initWithData:postData encoding:NSStringEncodingConversionAllowLossy];
NSLog(@"jsonString = %@", jsonString);
如果您想将此 postbody 设置为 http 请求并将其传递给服务器,您可以将其设置为,
[urlRequest setHTTPBody:postData];