从 json 解码 html 字符串

Decode html string from json

我如何解码这个字符串

"<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}

如何转义特殊字符 " ?

我想在视图中将字符串显示为属性字符串。

通过 playground 测试

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)

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 获取解码器(和编码器)的好工具。

您可以使用单引号使 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 文件中并从那里读取会更好

干杯