簡體   English   中英

從 WKWebView (Swift, iOS) 中的響應中解析 json 對象

[英]Parse json object from response inside WKWebView (Swift, iOS)

我正在嘗試從WKWebView請求接收 json 對象。 現在我只能從 body 獲取 html 字符串,但它包含在一些標簽中(比如<pre> )。 我怎么能不使用任何第三方庫呢? 並且還直接從響應中獲取身體?

我的代碼展示了我現在擁有的東西,但它沒有提供我需要的東西。 我正在使用WKNavigationDelegate委托方法和evaluateJavaScript方法來獲取正文的內部htmlText

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        webView.evaluateJavaScript("document.body.innerHTML") { (anyObject, error) in
            guard let htmlStr = anyObject as? String else {
                return 
            }
            let data: Data = htmlStr.data(using: .utf8)!
            do {
                let jsObj = try JSONSerialization.jsonObject(with: data, options: .init(rawValue: 0))
                if let jsonObjDict = jsObj as? Dictionary<String, Any> {
                    let threeDSResponse = ThreeDSResponse(dict: jsonObjDict)
                    print(threeDSResponse)
                }
            } catch _ {
                print("having trouble converting it to a dictionary")
            }
        }
    }

現在我收到 htmlStr 作為

"{\\"id\\":68324947,\\"is_test\\":false,\\"status\\":2,\\"status_description\\":\\"055 - 無效交易\\"}"

並希望直接從 json(parse it) 中獲取它

{\\"id\\":68324947,\\"is_test\\":false,\\"status\\":2,\\"status_description\\":\\"055 - 無效交易\\"}

我也不能使用 3part 庫,應該盡可能地純。

使用JSONDecoder

do {
    let dec = JSONDecoder()
    dec.keyDecodingStrategy = .convertFromSnakeCase
    let res = try dec.decode(Root.self, from:Data(htmlStr.utf8))
    print(res)
} catch  {
    print("having trouble converting it to a dictionary" , error)
}

struct Root : Codable {
    let id,status:Int
    let isTest:Bool
    let statusDescription:String
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM