json - 如何在 Swift 中解码 HTML 实体?

标签 json swift html-entities

我正在从网站中提取一个 JSON 文件,收到的字符串之一是:

The Weeknd ‘King Of The Fall’ [Video Premiere] | @TheWeeknd | #SoPhi

如何将 之类的内容转换为正确的字符?

我制作了一个 Xcode Playground 来演示它:

import UIKit

var error: NSError?
let blogUrl: NSURL = NSURL.URLWithString("http://sophisticatedignorance.net/api/get_recent_summary/")
let jsonData = NSData(contentsOfURL: blogUrl)

let dataDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

var a = dataDictionary["posts"] as NSArray

println(a[0]["title"])

最佳答案

此答案最后针对 Swift 5.2 和 iOS 13.4 SDK 进行了修订。


没有直接的方法可以做到这一点,但您可以使用 NSAttributedString 魔法使这个过程尽可能轻松(请注意,此方法也会去除所有 HTML 标记)。

记住仅从主线程初始化NSAttributedString。它使用 WebKit 来解析底层的 HTML,因此需要。

// This is a[0]["title"] in your case
let htmlEncodedString = "The Weeknd <em>&#8216;King Of The Fall&#8217;</em>"

guard let data = htmlEncodedString.data(using: .utf8) else {
    return
}

let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
    .documentType: NSAttributedString.DocumentType.html,
    .characterEncoding: String.Encoding.utf8.rawValue
]

guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {
    return
}

// The Weeknd ‘King Of The Fall’
let decodedString = attributedString.string
extension String {

    init?(htmlEncodedString: String) {

        guard let data = htmlEncodedString.data(using: .utf8) else {
            return nil
        }

        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ]

        guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {
            return nil
        }

        self.init(attributedString.string)

    }

}

let encodedString = "The Weeknd <em>&#8216;King Of The Fall&#8217;</em>"
let decodedString = String(htmlEncodedString: encodedString)

关于json - 如何在 Swift 中解码 HTML 实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53110195/

相关文章:

ios - CoreLocation 在 Today Extension 中不起作用

.net - 替代 System.Web.HttpUtility.HtmlEncode/Decode?

javascript - 在json对象中按值查找键名

ios - 为什么在使用 swift 语言的 ios 中使用 CryptoSwift 框架时会出现此错误?

swift - 使用 Swift 枚举减少函数中的参数数量

php - 取消转义用户输入的符号是否安全?

html-entities - Textile 中的 HTML 实体

xml - ASP.NET 网络 API : XMLFormatter thinks he can write Json-objects

java - Gson 在 "$Types.resolve"上溢出并出现 StackOverflow 异常

java - Json 转换错误预计为 : after key