我让我的GET方法正常工作并正确映射我返回的对象。现在我正在研究POST方法。我需要序列化一个多级JSON,特别是它有以下格式的3个级别
{
"name": "Test",
"version": "1",
"iconId": 1,
"runFrequency": 5,
"lastActionSummary": "Yesterday, 9:30am",
"description": "Test",
"id": 1,
"containers": [
{
"id": 1,
"triggers": [
{
"@class": "someClass",
"intValue": 90,
"operator": "equal",
"type": "Ttest"
}
]
}
]
}
我尝试过这样做,因为我对服务器的响应进行了对象映射但由于容器永远不会添加到JSON而失败。有关如何实现这一目标的任何想法? restkit示例没有显示多级JSON,所以他们没有帮助很多。
答案 0 :(得分:2)
看起来你想要的是一个包含各种字段的字典:
NSMutableDictionary *topDictionary = [[NSMutableDictionary alloc] init];
[topDictionary setObject:@"Test" forKey:@"name"];
[topDictionary setObject:@"1" forKey:@"version"];
...
然后,您有一个容器数组,每个数组项中都有一个字典:
NSMutableArray *containers = [[NSMutableArray alloc] init];
[topDictionary setObject:containers forKey:@"containers"];
NSMutableArray *arrayItem1 = [[NSMutableDictionary alloc] init];
[containers addObject:arrayItem1];
[arrayItem1 setObject:[NSNumber numberWithInteger:1] forKey:@"id"];
...
在容器下的每个词典中,你有一个触发器数组,同样该数组的每个项目都是字典:
NSMutableArray *triggers = [[NSMutableArray alloc] init];
[arrayItem1 setObject:triggers forKey:@"triggers"];
NSMutableArray *trigger1 = [[NSMutableDictionary alloc] init];
[triggers addObject:trigger1];
[trigger1 setObject:@"someClass" forKey:@"@class"];
...
这只是展示了如何在该容器中添加1个带有1个触发器的容器,但是你明白了。如果要在每个数组中放置多个项目,请转换为适当的循环。
一旦你有了这些词典(在一个数组中,在一个字典中,在一个数组中,在一个字典中......)你就有了一个可以干净地序列化为JSON的对象。
答案 1 :(得分:0)
您可能想要检查我的实现,以便将JSON序列化和反序列化为NSObject,反之亦然。 - https://github.com/QBurst/KVCObjectSerializer
答案 2 :(得分:0)
// create a JSON string from your NSDictionary
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:topDictionary
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSString *jsonString = [[NSString alloc] init];
if (!jsonData) {
NSLog(@"Got an error: %@", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
// make the post using the objectManager if you want to map the response to a model
RKObjectManager* objectManager = [RKObjectManager sharedManager];
[objectManager loadObjectsAtResourcePath:@"/api/" delegate:self block:^(RKObjectLoader* loader) {
loader.serializationMIMEType = RKMIMETypeJSON; // We want to send this request as JSON
loader.objectMapping = [objectManager.mappingProvider objectMappingForClass:[Plan class]];
loader.resourcePath = @"/api/";
loader.method = RKRequestMethodPOST;
loader.params = [RKRequestSerialization serializationWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON];
}];
答案 3 :(得分:0)
只是过去Flaviu回答的简单捷径。如果要将创建的字典作为请求主体JSON有效负载发送,只需使用以下命令:
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:resourcePath usingBlock:^(RKObjectLoader *loader) {
...
[loader setBody:topDictionary forMIMEType:RKMIMETypeJSON];
...
}];
您可以在RKRequest头文件(RKRequest.h)中找到更多信息。
- (void)setBody:(NSDictionary *)body forMIMEType:(NSString *)MIMEType;
我最好的