首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从WKWebView内部的响应解析json对象(Swift,iOS)

从WKWebView内部的响应解析json对象(Swift,iOS)
EN

Stack Overflow用户
提问于 2019-06-25 14:01:07
回答 1查看 2.6K关注 0票数 2

我正在尝试从WKWebView内部的请求中接收json对象。目前,我只能从body获得html字符串,但它被一些标记(如<pre>)所包装。我怎么能不使用第三部分库呢?也能直接从反应中得到身体?

我的代码演示了我现在拥有的东西,但它并没有提供我需要的东西。我使用WKNavigationDelegate的委托方法和evaluateJavaScript方法来获取身体的内部htmlText

代码语言:javascript
复制
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部分库,并且应该尽可能地使它变得更纯净。

EN

回答 1

Stack Overflow用户

发布于 2019-06-25 14:11:36

使用JSONDecoder

代码语言:javascript
复制
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)
}
代码语言:javascript
复制
struct Root : Codable {
    let id,status:Int
    let isTest:Bool
    let statusDescription:String
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56755846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档