AFNetworking을 사용하여 PUT을 수행하려고합니다. 경쟁에서 참가자의 배열을 보낼 필요가 있지만 "JSON에서 유효하지 않은 최상위 형식을 신속하게 작성"오류가 나타납니다. 내가 생성하는 JSON은 완벽합니다. REST Client를 사용하면 모든 것이 작동합니다.Swift에서 JSON 쓰기에 잘못된 최상위 유형이 있습니다.
*** 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 : 나는 응용 프로그램을 실행하고 요청을 보내는 경우
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
}
, 나는이 오류를 얻을 : I가 된 JSONObject를 만들어 내
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)
})
}
및 방법 : 여기 내 코드입니다 어디에 문제가 있는지 모르겠다 ... 내가 JSON에 넣은 속성은 NSObject이고 JSON에 넣은 모든 필드는 String (String 유형, NSString이 아님)이고 NSString을 사용하려고했지만 여전히 오류가 발생합니다. . 어떤 아이디어? Thx
쿨,하지만 지금은이 오류를 얻을 : 오류 도메인 = NSCocoaErrorDomain 코드 = 3840 "작업을 완료 할 수 없습니다. (코코아 오류 3840.) "(JSON 텍스트가 배열 또는 객체 및 옵션으로 시작되지 않아 조각을 설정할 수 없습니다.) UserInfo = 0x7fdee3753d10 {NSDebugDescription = JSON 텍스트가 배열 또는 객체로 시작되지 않아 조각을 설정할 수 없습니다.} – diegomen
스택 트레이스는 어디에 있습니까? 기본 디버깅에 대한 도움을 요청하는 것 같습니다. – gnasher729
이제 웹 서비스가 아무 것도 반환하지 않았기 때문에 마지막으로 오류가 발생했습니다. 이제는 "성공"을 반환하고 모든 것이 올바르게 작동합니다. 감사 Wain! – diegomen