【问题标题】:Swifty-JSON: unable to parse underscoreSwifty-JSON:无法解析下划线
【发布时间】:2020-01-02 11:53:45
【问题描述】:

有一个 json 文件,其 ____ 的值类似于 "question": "11 ____________" Swifty-json 无法解析并抛出错误The data couldn’t be read because it isn’t in the correct format.有没有办法处理这种情况?

JSON 响应 -

"typingQuestionArray": [
          {
            "head": "Type the number name for the following number.",
            "question": "11 ____________",
            "imageLink": "",
            "correctAnswer": "eleven"
          }
]

代码片段 -

if let path = getPath(name: chapterString){
    do {
           let data = try Data(contentsOf: path, options: .alwaysMapped)
           let json = try JSON(data: data)
           print(json)

        } catch let error {
            print("parse error: \(error.localizedDescription)")
        }
        } else {
            print("Invalid filename/path.")
    }

注意 - 不要怀疑 JSON 格式和 swift 代码。唯一的问题是 JSON 格式的 _____

json 验证的屏幕截图 -

【问题讨论】:

  • 显示代码并完成json
  • @Sh_Khan 代码已更新。完整的 json 很大,这里不能粘贴,但我已经在 J​​SON Viewer 上验证过了。请检查
  • json 环绕 {} ??同时删除, options: .alwaysMapped
  • @Sh_Khan Json 有效。我只粘贴了一小块 json 并且已经使用了 .总是映射
  • 由于您知道确切的位置 (2396),您可以轻松找出导致错误的字符。

标签: swift parsing swifty-json


【解决方案1】:

我了解您正在使用 Swifty-JSON,但如果您不急于使其工作,看起来JSONDecoder 可以完成工作:

let data = """
{
    "head": "Type the number name for the following number.",
    "question": "11 ____________",
    "imageLink": "",
    "correctAnswer": "eleven"
}
""".data(using: .utf8)!

你没有发布你的结构,但我猜它看起来像这样:

struct Question: Codable {
    let head: String
    let question: String
    let imageLink: String
    let correctAnswer: String
}

解码:

let question = try! JSONDecoder().decode(Question.self, from: data)

然后可以打印问题:

print (question)
// Output:
///Question(head: "Type the number name for the following number.", question: "11 ____________", imageLink: "", correctAnswer: "eleven")

如果您对JSONDecoder 的解决方案不感兴趣,请告诉我,我很乐意删除此答案。

【讨论】:

    【解决方案2】:

    已通过将 Tab 替换为 Whitespace 解决了此问题。

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      相关资源
      最近更新 更多