【问题标题】:从 json 解码 html 字符串
【发布时间】: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 放在字符串中吗?您可以将其保存在文件中

标签: json swift struct decode


【解决方案1】:

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

【讨论】:

  • 谢谢,我看到 StackOverflow 与我编写的代码混淆,并删除了 \n 后面的所有内容。简化了 json,使其正确显示。
  • @andredewaard 在您更改后我已经更新了我的答案。
  • 只有当代码中有json字符串时才需要\\,原来的json不需要需要更改。
  • @JoakimDanielson 没错,这是您使用这些多行文字字符串的时候。
【解决方案2】:

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

干杯?

【讨论】:

  • 直截了当没有?
猜你喜欢
  • 2013-03-12
  • 2019-04-03
  • 2011-08-30
  • 2010-11-09
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多