【问题标题】:How to deal apostrophe in JSON from webservice? [duplicate]如何处理来自 web 服务的 JSON 中的撇号? [复制]
【发布时间】:2017-03-24 07:13:10
【问题描述】:

我正在使用 NSURLSession 与 Web 服务进行通信。但是,在来自 Webservice 的 JSON 中,我得到了这样的字符串 Biblotecas de cat& aacute;logos de Marcas,即 Biblotecas de catálogos de Marcas。我需要摆脱文本 cat& aacute;logos 并获取原始字符串。我怎样才能做到这一点。 我正在使用此代码来解析 JSON。

guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] else{

                self.showalertview(messagestring: parseError)
                return
            }

【问题讨论】:

  • 我可以查看您的示例回复吗?
  • @anilkukdeja { data = ( { description = "Biblotecas de catálogos de Marcas"; name = "Biblotecas de catálogos de Marcas"; } );味精 = u00e9xito;结果 = 1; }

标签: ios json string swift3


【解决方案1】:

最好的方法是要求网络服务的所有者发送符合 UTF-8 标准的文本。

如果这是不可能的NSAttributedString 可以以非常方便的方式解码 HTML 实体,这是一个 String 扩展添加计算属性 htmlDecoded。由于转换可能由于多种原因而失败,因此返回值是可选的:

extension String {
    var htmlDecoded : String? {
        guard let encodedString = self.data(using: .utf8) else { return nil }
        let options : [String:Any] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue]
        return  try? NSAttributedString(data: encodedString, options: options, documentAttributes: nil).string
    }
}

并使用它:

let string = "Biblotecas de catálogos de Marcas"
print(string.htmlDecoded) // "Biblotecas de catálogos de Marcas"

【讨论】:

  • 谢谢,我会试试这个代码。
  • 你拯救了我的一天..!谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
  • 2011-03-19
  • 2015-12-02
  • 2018-12-16
相关资源
最近更新 更多