Swift中JSON写入中的无效顶级类型 [英] Invalid top-level type in JSON write in Swift

查看:110
本文介绍了Swift中JSON写入中的无效顶级类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AFNetworking进行PUT。我需要在竞赛中发送一组参与者,但出现在Swift中写入JSON无效的顶级类型错误。我生成的JSON非常完美,如果我使用REST Client尝试使用,一切都会正常。这是我的代码:

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)
    })
}

然后我创建JSONObject的方法:

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

我不不知道问题出在哪里...那个公关的对象我放入JSON的操作是一个NSObject,我放入JSON的所有字段都是字符串(字符串类型,不是NSString),我尝试使用NSString,但仍然出现错误。有任何想法吗?? Thx

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

推荐答案

您要自己进行JSON序列化,然后要求AFN再次进行序列化,因此您正在传递 NSString 并要求将其序列化为JSON,这将不起作用。

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.

您应该做的是传递从 createDictionaryOfParticipations 返回的 NSArray 代替:

What you should be doing is passing the NSArray returned from createDictionaryOfParticipations instead:

self.requestManager?.PUT(kParticipantsUrl, parameters: self.createDictionaryOfParticipations(), success:...

这篇关于Swift中JSON写入中的无效顶级类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆