我正在尝试使用AFNetworking进行PUT。我需要在竞赛中发送一组参与者,但是我得到了“在Swift中JSON写入的无效顶级类型”错误。我生成的JSON是完美的,如果我使用REST Client尝试它,一切正常。这是我的代码:
func sendUsers(onComplete: (NSError?) -> Void) {
var error: NSError?
var jsonData: NSData = NSJSONSerialization.dataWithJSONObject(self.createDictionaryOfParticipations(), options: NSJSONWritingOptions.allZeros, error: &error)!
var jsonString: String = NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
println("Json: \(jsonString)")
if self.requestManager == nil {
self.requestManager = AFHTTPRequestOperationManager();
}
self.requestManager?.responseSerializer = AFJSONResponseSerializer();
let requestSerializer = AFJSONRequestSerializer()
self.requestManager?.requestSerializer = requestSerializer;
self.requestManager?.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type");
self.requestManager?.PUT(kParticipantsUrl, parameters: jsonString, success: { (operation: AFHTTPRequestOperation!, object: AnyObject!) -> Void in
self.persistUsers([])
onComplete(nil)
}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
onComplete(error)
})
}
我的方法是创建JSONObject:
func createDictionaryOfParticipations() -> NSArray {
var dict: NSMutableDictionary = NSMutableDictionary()
var participants: NSMutableArray = NSMutableArray()
var savedParticipants: [User] = self.getUsers() as [User]
for participant: User in savedParticipants {
var participantDict: NSMutableDictionary = NSMutableDictionary()
participantDict.setValue(participant.name, forKey: kNameKey)
participantDict.setValue(participant.firstSurname, forKey: kFirstSurnameKey)
participantDict.setValue(participant.secondSurname, forKey: kSecondSurnameKey)
participantDict.setValue(participant.dni, forKey: kDniKey)
participantDict.setValue(participant.address, forKey: kAddressKey)
participantDict.setValue(participant.postalCode, forKey: kPostalCodeKey)
participantDict.setValue(participant.city, forKey: kCityKey)
participantDict.setValue(participant.province, forKey: kProvinceKey)
participantDict.setValue(participant.phone, forKey: kPhoneKey)
participantDict.setValue(participant.email, forKey: kEmailKey)
participantDict.setValue(participant.code, forKey: kCodeKey)
participantDict.setValue(participant.prize, forKey: kPrizeKey)
participants.addObject(participantDict)
}
return participants
}
如果我运行应用程序并发送请求,我会收到此错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
*** First throw call stack:
(
0 CoreFoundation 0x0000000103b5df35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001037f6bb7 objc_exception_throw + 45
2 CoreFoundation 0x0000000103b5de6d +[NSException raise:format:] + 205
3 Foundation 0x000000010349b0ea +[NSJSONSerialization dataWithJSONObject:options:error:] + 264
4 MLB 0x00000001031cb23c -[AFJSONRequestSerializer requestBySerializingRequest:withParameters:error:] + 1164
5 MLB 0x00000001031c13bd -[AFHTTPRequestSerializer requestWithMethod:URLString:parameters:error:] + 1869
6 MLB 0x00000001031e6d14 -[AFHTTPRequestOperationManager PUT:parameters:success:failure:] + 388
7 MLB 0x000000010317acf0 _TFC3MLB12UsersManager9sendUsersfS0_FFGSqCSo7NSError_T_T_ + 8656
8 MLB 0x0000000103166426 _TFC3MLB22MainMenuViewController9alertViewfS0_FTCSo11UIAlertView20clickedButtonAtIndexSi_T_ + 630
9 MLB 0x0000000103166602 _TToFC3MLB22MainMenuViewController9alertViewfS0_FTCSo11UIAlertView20clickedButtonAtIndexSi_T_ + 66
10 UIKit 0x00000001046773e0 -[UIAlertView _prepareToDismissForTappedIndex:] + 161
11 UIKit 0x0000000104676ede __35-[UIAlertView _prepareAlertActions]_block_invoke50 + 43
12 UIKit 0x0000000104670464 -[UIAlertController _dismissAnimated:triggeringAction:triggeredByPopoverDimmingView:] + 89
13 UIKit 0x00000001047c6540 _UIGestureRecognizerUpdate + 9487
14 UIKit 0x000000010445eff6 -[UIWindow _sendGesturesForEvent:] + 1041
15 UIKit 0x000000010445fc23 -[UIWindow sendEvent:] + 667
16 UIKit 0x000000010442c9b1 -[UIApplication sendEvent:] + 246
17 UIKit 0x0000000104439a7d _UIApplicationHandleEventFromQueueEvent + 17370
18 UIKit 0x0000000104415103 _UIApplicationHandleEventQueue + 1961
19 CoreFoundation 0x0000000103a93551 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
20 CoreFoundation 0x0000000103a8941d __CFRunLoopDoSources0 + 269
21 CoreFoundation 0x0000000103a88a54 __CFRunLoopRun + 868
22 CoreFoundation 0x0000000103a88486 CFRunLoopRunSpecific + 470
23 GraphicsServices 0x00000001084ca9f0 GSEventRunModal + 161
24 UIKit 0x0000000104418420 UIApplicationMain + 1282
25 MLB 0x000000010319f84e top_level_code + 78
26 MLB 0x000000010319f88a main + 42
27 libdyld.dylib 0x000000010679c145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
我不知道问题出在哪里...我放入JSON的属性的对象是NSObject,我放入json的所有字段都是字符串(字符串类型,而不是NSString),我试过使用NSString,但我仍然得到错误。有任何想法吗?? THX
答案 0 :(得分:1)
您自己正在进行JSON序列化,然后要求AFN再次执行此操作,因此您传递NSString
并要求将其序列化为JSON,这将无效。
您应该做的是传递从NSArray
返回的createDictionaryOfParticipations
:
self.requestManager?.PUT(kParticipantsUrl, parameters: self.createDictionaryOfParticipations(), success:...