如何使用SwiftyJSON从Swift中的JSON字符串中获取值?

时间:2016-08-25 18:28:03

标签: json swift swifty-json

我有一个JSON字符串,想从中获取一些值。我正在使用SwiftyJSON从JSON字符串中提取一些值。但不确定为什么我从中得到空值。如何使用version, ephemeralPublicKey, transactionId从此JSON字符串中检索SwiftyJSON等所有值?

代码:

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

输出:

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

version = 

输出解决方案:

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==

1 个答案:

答案 0 :(得分:1)

JSON(decryptedPaymentData)只构造一个JSON对象,它是一个字符串"{\"version\":...}"

要解析它,您需要使用parse()函数:

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

请注意,您不需要自己将NSData转换为NSString,因为您可以使用init(data:options:error:)构造函数:

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