json - swift 4 : JSONDecoder fails in one specific case - "The operation could not be completed"

标签 json swift decode codable jsondecoder

<分区>

我正在接收 JSON 文本,将其转换为数据,然后使用 JSONDecoder 创建由 JSON 文本/字符串表示的具体类型。

它确实适用于我的“复杂”数据结构(它实现了 Codable),甚至是一个简单的 Int 数组,如下所示:

import Foundation

let jsonTextContainigArrayOfInt: String = "[1,2,3]"
let data = jsonTextContainigArrayOfInt.data(using: .utf8)!

do {
    let arrayOfInt: [Int] = try JSONDecoder().decode([Int].self, from: data)
    for n in arrayOfInt {
        print(n)
    }
}
catch {
    print(error)
}

前面的代码可以正常工作并正确创建 Int 数组并打印它们。

当对 JSON 文本中的单个 Int 执行相同的方法时会出现问题:

import Foundation

let jsonTextContainigOneInt: String = "1"
let data = jsonTextContainigOneInt.data(using: .utf8)!

do {
    let myInt: Int = try JSONDecoder().decode(Int.self, from: data)
    print(myInt)
}
catch {
    print(error)
}

对于第二种方法,我收到以下错误:

"The operation could not be completed"

*** 编辑 ***

此错误报告已存在:https://bugs.swift.org/browse/SR-6163

最佳答案

JSONDecoder 只能将集合类型(数组或字典)解码为根对象。

在引擎盖下 JSONDecoder 使用 JSONSerialization 没有任何选项。但是,要解码 StringInt,您必须指定 .allowFragments 选项。

使用 JSONSerialization.allowFragments 选项

let jsonTextContainingOneString = "1"
let data = Data(jsonTextContainingOneString.utf8)

do {
    let myString = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
    print(myString)
}
catch {
    print(error)
}

关于json - swift 4 : JSONDecoder fails in one specific case - "The operation could not be completed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50006047/

相关文章:

javascript - 按特定条件重新排列 json 文件内容

java - 如何在 json [android] 中检索天气数据

python - 将 Pandas Dataframe 转换为自定义嵌套 JSON

swift - 如何快速检查用户点击图像的点击次数

php - 在php中读取unicode文件

javascript - 数据表不显示内容的简单示例

swift - 类型 'CustomObject' 的值不符合预期的字典值类型 'AnyObject'

ios - 调用 collectionView(_ :layout:sizeForItemAt:) in Swift 4

react-native - 在 React Native Expo 应用程序中解码没有 key 的 JWT token

c - 不使用 OpenMAX 在 Raspberry Pi 中解码视频?