Swift 快速JSON:无法分析下划线
有一个json文件的值是Swift 快速JSON:无法分析下划线,swift,parsing,swifty-json,Swift,Parsing,Swifty Json,有一个json文件的值是
无法读取数据,因为它的格式不正确。
有什么方法可以处理这种情况吗
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,但如果您不急于让它工作,那么
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
的解决方案不感兴趣,请告诉我,我将很乐意删除此答案。此问题已通过将选项卡
替换为空白
显示代码并完成来解决json@Sh_Khan代码已更新。完整的json非常大,不能粘贴到这里,但我已经在json查看器上验证过了。请用{}
选中JSON环绕符号??同时删除,选项:.alwaysMapped
@Sh_Khan Json有效。我只粘贴小块json,并且已经使用过了。通常,由于您知道确切位置(2396),您可以轻松找出导致错误的字符。