我有一个字符串JSON,但是其中有花哨的弯引号,这使NSJSONSerialization失败。
let str = "{“title”:\"this is a “test” example\"}"
try! JSONSerialization.jsonObject(with: str.data(using: .utf8)!) // Error
title
周围的引号是双引号,显然JSONSerialization无法处理它并失败。幼稚的方法是简单地将卷曲引用的所有实例替换为非卷曲的实例。这种方法的问题在于它将更改test
周围的弯引号,不应更改! title
周围的引号可以更改,但test
周围的引号不能更改。
如何解决此问题?
如果仅将弯引号用于键,则此正则表达式将完成此工作:
let str = "{“title”:\"this is a “test” example\"}"
let strFixed = str.replacingOccurrences(
of: #"“(.*)”:\"(.*)\""#,
with: "\"$1\":\"$2\"",
options: .regularExpression
)
let json = try! JSONSerialization.jsonObject(with: strFixed.data(using: .utf8)!)
如果打印json
,则会得到正确的结果:
{
title = "this is a \U201ctest\U201d example";
}