我正在尝试从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,\“状态\”:2,\"status_description\":\"055 -无效事务\“}”
并希望将其直接作为json(解析它)从
{“id\”:68324947,\"is_test\":false,\"status\":2,\"status_description\":\"055 -无效事务\“}
另外,我不能使用3部分库,并且应该尽可能地使它变得更纯净。
发布于 2019-06-25 14:11:36
使用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
}https://stackoverflow.com/questions/56755846
复制相似问题