OGeek|极客世界-中国程序员成长平台

标题: ios - swift 3,JSON,编写时顶级类型无效 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:00
标题: ios - swift 3,JSON,编写时顶级类型无效

我有两个完全正确的 json 对象,一个是从函数创建的,另一个是硬编码的,硬编码的一个有效,另一个无效(它总是提示错误 invalid top-level type ,这很奇怪。任何提示?Tks

let myData = self.dailyMileage?.toDictionary()

let directData = ["orgId" : self.orgId, "driverId" : self.driverId, "date" : Utils.getTodaysDate() ] as [String : Any]

//this won't work unless I substitute myData with directData                        
let jsonData = try JSONSerialization.data(withJSONObject: myData, options: .prettyPrinted)

//this is the function that produces myData, and nothing is nil
 public func toDictionary() -> [String : Any] {
    let dict = [ "orgId" : orgId , "driverId": driverId, "date" : date] as [String : Any]
    return dict
}



Best Answer-推荐答案


文档中给出的

JSONSerialization:

An object that may be converted to JSON must have the following properties:

The top level object is an NSArray or NSDictionary. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

All dictionary keys are instances of NSString. Numbers are not NaN or infinity.

Other rules may apply. Calling isValidJSONObject(_ or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.

  1. 我认为来自函数的那个​​可能有一个 NSDate 对象而不是一个 NSString 对象。

  2. 另一个原因是因为您的 myData 对象是可选的。 JSONSerialization 可能会出现错误,例如对象是可选的。

请检查是否是由于这两个原因之一。随时提出修改建议以使其变得更好。

关于ios - swift 3,JSON,编写时顶级类型无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40453343/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4