user2325154 user2325154 - 3 months ago 13
JSON Question

How to get a value from JSON string in Swift using SwiftyJSON?

I have a

JSON
string and would like to obtain some values from it. I am using
SwiftyJSON
to extract some values from the JSON string. But not sure why I am getting empty values from it. How can I retrieve all the values such as
version, ephemeralPublicKey, transactionId
etc from this JSON string using
SwiftyJSON
?

Code:

let decryptedPaymentData:NSString! = NSString(data: encryptedPaymentData, encoding: NSUTF8StringEncoding)
print("decryptedPaymentData = \(decryptedPaymentData)")

//extract values here
let decryptedJsonStr = JSON(decryptedPaymentData)
let version = decryptedJsonStr["version"].stringValue
print("version = \(version)")


Output:

decryptedPaymentData = {"version":"EC_v1",
"header":{
"ephemeralPublicKey":"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE1AhSWKm/KoXMmRU/dm825c8M3HZUYH/X8SH2zvzLgF9AN0ifWNH6KMLdRXhYSbnhVv0eDz+cJhf0I6o3oSc1bg==","publicKeyHash":"y9Gi+xcoSJjzegmkLQJ1KB7oehqavQom5EDwNCv+nHE=","transactionId":"7f83d3eff0de5d1313b6689d274d29dd7f71fe3763829f488ff4ac23a3dd40c5"}
}

version =


Solution with Output:

let decryptedJsonStr = JSON.parse(decryptedPaymentData as String)
let version = decryptedJsonStr["version"].stringValue
let epk = decryptedJsonStr["header"]["ephemeralPublicKey"].stringValue
print("version = \(version)")
print("epk = \(epk)")

version = EC_v1
epk=MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEoyXCcna7anfdPXVJcRFF6+SOgCgCqRqcdx/p0YrTy3nUU1LQ977EwuddRvnHKi5WemLnWIf3AzPDGLMY1L2Pog==

Answer

JSON(decryptedPaymentData) just constructs a JSON object which is a string "{\"version\":...}".

To parse it, you need to use the parse() function:

let decryptedJsonStr = JSON.parse(decryptedPaymentData)
//                          ^^^^^

Note that you don't need to convert the NSData into NSString yourself, as you could use the init(data:options:error:) constructor:

let decryptedJsonStr = JSON(data: encryptedPaymentData)
//                          ^^^^^