奇怪的 json 解码器行为
Weird json decoder behaviour
所以,我有从通知中获得的 userInfo 数据,我想解码并将该数据传递给另一个 class。我将 swiftyJSON 用于 json 解码器。这是我的代码:
func decodedNotificationTransactionData(data: Any, completionHandler: @escaping (_ dict: [String : Any]) -> ()){
let dict = JSON(data)
print ("this is json data \(dict)")
print("this is status \(dict["status"])")
let test = [
"id" : "\(dict["id"])",
"orderDate" : "\(dict["orderDate"])",
"patientName" : "\(dict["patient"]["fullName"])",
"patientAddress" : "\(dict["patient"]["address"])",
"caregiverName" : "\(dict["care"]["fullName"])",
"caregiverAddress" : "\(dict["care"]["address"])",
"serviceType" : "\(dict["service"]["label"])",
"status" : "\(dict["status"])",
"price" : "\(dict["totalAmount"])",
"otherNote" : "\(dict["otherNote"])",
"totalService" : dict["detailDatas"].count,
"serviceLongType" : dict["detailDatas"][0]["type"],
"jsonContent" : dict
] as [String : Any]
completionHandler(test)
}
this the "print ("this is json data (dict)")" result
当代码到达 print ("this is json data (dict)") 时数据就在那里没有问题但是当代码到达 print("this is status (dict["status"])") 它在日志中给出空值。您遇到过同样的问题吗?
快速查看 SwiftyJSON 文档立即发现错误:
Creates a JSON object.
- parameter object: the object.
- note: this does not parse a String
into JSON, instead use init(parseJSON: String)
.
- returns: the created JSON object
public init(_ object: Any) {
所以你必须使用
let dict = JSON(parseJSON: data)
所以,我有从通知中获得的 userInfo 数据,我想解码并将该数据传递给另一个 class。我将 swiftyJSON 用于 json 解码器。这是我的代码:
func decodedNotificationTransactionData(data: Any, completionHandler: @escaping (_ dict: [String : Any]) -> ()){
let dict = JSON(data)
print ("this is json data \(dict)")
print("this is status \(dict["status"])")
let test = [
"id" : "\(dict["id"])",
"orderDate" : "\(dict["orderDate"])",
"patientName" : "\(dict["patient"]["fullName"])",
"patientAddress" : "\(dict["patient"]["address"])",
"caregiverName" : "\(dict["care"]["fullName"])",
"caregiverAddress" : "\(dict["care"]["address"])",
"serviceType" : "\(dict["service"]["label"])",
"status" : "\(dict["status"])",
"price" : "\(dict["totalAmount"])",
"otherNote" : "\(dict["otherNote"])",
"totalService" : dict["detailDatas"].count,
"serviceLongType" : dict["detailDatas"][0]["type"],
"jsonContent" : dict
] as [String : Any]
completionHandler(test)
}
this the "print ("this is json data (dict)")" result
当代码到达 print ("this is json data (dict)") 时数据就在那里没有问题但是当代码到达 print("this is status (dict["status"])") 它在日志中给出空值。您遇到过同样的问题吗?
快速查看 SwiftyJSON 文档立即发现错误:
Creates a JSON object.
- parameter object: the object.
- note: this does not parse aString
into JSON, instead useinit(parseJSON: String)
.
- returns: the created JSON objectpublic init(_ object: Any) {
所以你必须使用
let dict = JSON(parseJSON: data)