以下代码引发了一个异常,我无法弄清楚出了什么问题:
-(NSDictionary*)prepareParameters:(NSArray*) p_currentParameters
{
NSMutableDictionary *parameters = nil;
if(self.p_currentParameters.count > 0 )
{
parameters = [[NSMutableDictionary alloc] init];
for(int courseIdx = 0; courseIdx < p_currentParameters.count; courseIdx++)
{
CourseDetails* course = p_currentParameters[courseIdx];
NSMutableDictionary *courseData = [[NSMutableDictionary alloc] init];
courseData[@"courseIdx"] = [NSNumber numberWithInteger:course.id];
courseData[@"isFavorite"] = @(course.isFavorite);
courseData[@"isDeleted"] = @(course.isDeleted);
[parameters setObject:courseData forKey:[NSNumber numberWithInt:courseIdx]];
}
}
return parameters;
}
- (void)sendUserDataOnCourses:(NSArray*) p_currentCourses
{
@try
{
NSString *baseURLString = <API ADDRESS>;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setObject:userUniqueId forKey:@"userID"];
[parameters setObject:[self prepareParameters:p_currentCourses] forKey:@"courses"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[manager POST:baseURLString
parameters:[[NSDictionary alloc] initWithObjectsAndKeys:jsonString, @"request",nil]
success:^(AFHTTPRequestOperation *operation, id responseObject){
<DO SOME STUFF>
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(@"!!!!!!!!!!!!!! Error: %@ Error code: %d timeout counter:%d", error, error.code, timeoutfailure);
}];
}
@catch (NSException *exception)
{
NSLog(@"sendUserDataOnCourses exception: %@",exception);
}
}
此行发生异常:NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
,异常消息为:Invalid (non-string) key in JSON dictionary
。
答案 0 :(得分:0)
正如异常所说,您正在尝试将非字符串键(基本上是一个对象)插入到字典中。 JSON序列化方法可能不知道如何序列化该对象,因为它可能无法实现可序列化协议。我要做的是回顾你想要插入字典的每个对象/值,看看它是什么。然后要么使它们可序列化,要么将它们插入字符串形式。