我怎樣才能解碼這個字串
"<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)
uj5u.com熱心網友回復:
JSON 似乎不正確。"的值末尾似乎缺少一個"content":。
編輯:
你更新后,我又看了一遍。您需要在字串中轉義雙引號。奇怪的是,在這種情況下(當 JSON 在多行字串中時),您還需要轉義轉義字符(即\\)以正確解碼 JSON 并獲得可以使用的字串。
例子:
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 article = try JSONDecoder().decode(ArticleModel.self, from: jsonData)
print(article) // ArticleModel(id: 5, title: "iOS and iPadOS 14: The MacStories Review", content: "<div id=\"readability-page-1\" class=\"page\">test<div>")
順便說一下,https://app.quicktype.io/是一個很好的工具,可以為你的 JSON 獲取解碼器(和編碼器)。
uj5u.com熱心網友回復:
您可以使用單引號使 json 看起來更好,它仍然是有效的 HTML
let realJson = "{\"id\": 5,\"title\": \"iOS and iPadOS 14: The MacStories Review\",\"content\": \"<div id='readability-page-1' class='page'>test<div>\"}"
func parseJson(for json: String?) -> ArticleModel? {
guard let json = json, let jsonData = json.data(using: .utf8) else { return nil }
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
guard let article = try? decoder.decode(ArticleModel.self, from: jsonData) else { return nil }
return article
}
let article = parseJson(for: realJson)
print(article?.id ?? 0)
struct ArticleModel: Codable, Identifiable {
let id: Int
let title: String
let content: String
}
伊莫。對于更具可讀性的代碼,也許將 JSON 放在 .txt 檔案中并從那里讀取它會更好
干杯??
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/388860.html
上一篇:匯入APIjson資料并轉換為csv以在python中匯出到Excel
下一篇:使用打字稿測驗JSON
