动态属性是在iOS中使用Restkit发布JSON的关键

时间:2012-03-08 06:44:11

标签: ios json restkit

我正在使用RestKit 0.9.4。我想发布一个JSON,它有一个需要从对象属性填充的键。 JSON如下:

{
    "types":[ {
        "1" : "value1"
     },
     {  
         "7" : "value2"
     } ]
} 

我有一个对象,其中包含两个名为keytype和value的NSString数据成员。 keytype是一个变量,它具有上面嵌套json中键的值(上面的“1”,“7”等)。 mapKeyOfNestedDictionaryToAttribute 可能无法在此处运行,因为动态属性(用作键)位于最内层。 可以使用RestKit发布吗?

1 个答案:

答案 0 :(得分:1)

以下是如何在NSDictionary中创建该结构,然后使用RestKit将其发布为JSON。此外,响应然后映射到模型。

// make the inner dictionaries (probably would use a for loop for this
NSDictionary *dict1 = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"1", nil];
NSDictionary *dict7 = [[NSDictionary alloc] initWithObjectsAndKeys:@"value2", @"7", nil];
// put them in an array
NSArray *types = [[NSArray alloc] initWithObjects:dict1, dict7, nil];
// now put the array in a dictionary
NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:types, @"types", nil];

// create a JSON string from your NSDictionary
NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:finalDict 
                                                   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];
}];