代码之家  ›  专栏  ›  技术社区  ›  B K.

在swift中将HTML字符串解析为JSON

  •  0
  • B K.  · 技术社区  · 7 年前

    我正在使用javascript来显示字符串,使用HTML来WKWebView

    在我的视图控制器中调用Javascript函数

    myWebView.evaluateJavaScript("customMessageWithDictionary('\(self.jsonString)','\(strTestType)')") {
                (id, error) in
                print(error ?? "")
            }
    

    function customMessageWithDictionary(nameDetails,testType1) {
    
            nameDetails = nameDetails.replace(/\\/g, '');
            questionList = $.parseJSON(nameDetails);
            var iterator=0
            for (iterator = 0; iterator < questionList.length; iterator++)
                questionList[iterator].UserGivenAnswerId= null;
    
            questionObj = questionList[positionObj];
            testType=testType1;
    
            loadQuestions(true);
        }
    

    如果在 jsonString公司 因此,获取错误,我的Javascript就不会运行。因此WKWebview不显示内容。

    如果HTML标记在jsonString中,请给出解决方案,以便使用HTML字符串加载javascript函数。

    1 回复  |  直到 7 年前
        1
  •  1
  •   B K.    7 年前
     if let theJSONData = try?  JSONSerialization.data( withJSONObject: self.aryOfQuestionList,options: .prettyPrinted ),
    
    let theJSONText = String(data: theJSONData,encoding: String.Encoding.ascii) 
    {
       print("JSON string = \n\(theJSONText)")
    
       self.jsonString = (theJSONText as AnyObject) as! String
    }
    
    let regex = try! NSRegularExpression(pattern: "(?<=<\\w{1,40})\\s[^>]+(?=>)", options: .caseInsensitive)
    let range = NSMakeRange(0, self.jsonString.count)
    let htmlWithoutInlineAttributes = regex.stringByReplacingMatches(in: self.jsonString, options: [], range: range, withTemplate: "")
    
     print(htmlWithoutInlineAttributes)
    
        2
  •  -1
  •   AtulParmar    7 年前

    要检索应用程序资源的url,应该使用NSBundle类的URLForResource方法。

    斯威夫特2

    let url = NSBundle.mainBundle().URLForResource("privacy", withExtension:"html") 
    

    let url = Bundle.main.url(forResource: "privacy", withExtension: "html")