问题
i'm trying to do a PUT using AFNetworking. I need to send an array of participants in a competition, but i'm getting the "Invalid top-level type in JSON write in Swift" error. The JSON I generate is perfect, and if I try it using REST Client everything works. Here's my code:
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)
})
}
And the method within I create the 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
}
If I run the app and send the request, I get this error:
*** 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
I don't know where's the problem... the object which properties I put into the JSON is a NSObject and all the fields I put into the json are Strings (String type, not NSString) and I've tried to used NSString but I still get the error. Any ideas?? Thx
回答1:
You're doing the JSON serialisation yourself, and then asking AFN to do it again, so you're passing an NSString
and asking it to be serialised to JSON, which won't work.
What you should be doing is passing the NSArray
returned from createDictionaryOfParticipations
instead:
self.requestManager?.PUT(kParticipantsUrl, parameters: self.createDictionaryOfParticipations(), success:...
来源:https://stackoverflow.com/questions/27166711/invalid-top-level-type-in-json-write-in-swift