Ega Setya Putra
Ega Setya Putra

Reputation: 1695

Weird json decoder behaviour

So, I have userInfo data that I got from notification and I want to decode and pass this data to another class. I use swiftyJSON for json decoder. This is my code:

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

json data

When the code reach print ("this is json data (dict)") the data is there with no problem but when the code reach print("this is status (dict["status"])") it gives null on the log. Have you ever experienced the same issue?

Upvotes: 0

Views: 76

Answers (1)

vadian
vadian

Reputation: 285079

A quick look in the SwiftyJSON documentation reveals the error immediately:

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

So you have to use

let dict = JSON(parseJSON: data)

Upvotes: 3

Related Questions