【发布时间】:2022-01-23 02:12:46
【问题描述】:
我怎样才能解码这个字符串
"<div id=\"readability-page-1\" class=\"page\">test<div>"
我从一个 api 接收到这个对象,我想把它解码成一个结构:
{
"id": 5,
"title": "iOS and iPadOS 14: The MacStories Review",
"content": "<div id=\"readability-page-1\" class=\"page\">test<div>"
}
struct ArticleModel: Codable, Identifiable {
let id: Int
let title: String
let content: String
}
但是这会引发错误
debugDescription : "The given data was not valid JSON."
▿ underlyingError : Optional<Error>
- some : Error Domain=NSCocoaErrorDomain Code=3840 "Badly formed object around line 45, column 25." UserInfo={NSDebugDescription=Badly formed object around line 45, column 25., NSJSONSerializationErrorIndex=1437}
如何转义特殊字符“?
我想在视图中将字符串显示为属性字符串。
通过游乐场测试
import UIKit
let json = """
{
"id": 5,
"title": "iOS and iPadOS 14: The MacStories Review",
"content": "<div id=\"readability-page-1\" class=\"page\">test<div>"
}
"""
struct ArticleModel: Codable, Identifiable {
let id: Int
let title: String
let content: String
}
let jsonData = json.data(using: .utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let article = try decoder.decode(ArticleModel.self, from: jsonData)
print(article)
【问题讨论】:
-
与 API 提供者交谈,他们的 JSON 无效且无法解析
-
更新了 json,因为我看到 StackOverflow 弄乱了我的 json 以删除
\n后面的所有内容。我现在提供的 json 可以通过 swift 验证但不能解码 -
你的 JSON 似乎对我有效
-
您需要将 json 放在字符串中吗?您可以将其保存在文件中