gpt4 book ai didi

ios - swift 3,JSON,写入时无效的顶级类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:56:16 25 4
gpt4 key购买 nike

我有两个完全 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
}

最佳答案

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com