[英]Parse json object from response inside WKWebView (Swift, iOS)
I'm trying to receive json object from request inside WKWebView
.我正在尝试从WKWebView
请求接收 json 对象。 For now I can only get html string from body, but it wrapped in some tags (like <pre>
).现在我只能从 body 获取 html 字符串,但它包含在一些标签中(比如<pre>
)。 How I can do it not using any third part libs?我怎么能不使用任何第三方库呢? And also get body directly from response?并且还直接从响应中获取身体?
My code demonstrate what I have now and it doesn't provide me what I need.我的代码展示了我现在拥有的东西,但它没有提供我需要的东西。 I'm using delegate methods of WKNavigationDelegate
and evaluateJavaScript
method to get inner htmlText
of body我正在使用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")
}
}
}
Now I receive htmlStr as现在我收到 htmlStr 作为
"{\\"id\\":68324947,\\"is_test\\":false,\\"status\\":2,\\"status_description\\":\\"055 - Invalid transaction\\"}" "{\\"id\\":68324947,\\"is_test\\":false,\\"status\\":2,\\"status_description\\":\\"055 - 无效交易\\"}"
and want to get it directly as json(parse it) from并希望直接从 json(parse it) 中获取它
{\\"id\\":68324947,\\"is_test\\":false,\\"status\\":2,\\"status_description\\":\\"055 - Invalid transaction\\"} {\\"id\\":68324947,\\"is_test\\":false,\\"status\\":2,\\"status_description\\":\\"055 - 无效交易\\"}
also I can't use 3part libs and should make as much pure as It can be.我也不能使用 3part 库,应该尽可能地纯。
Use JSONDecoder
使用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.