【问题标题】:Parse JSON file with no objects Swift解析没有对象 Swift 的 JSON 文件
【发布时间】:2020-03-21 21:28:45
【问题描述】:

我正在尝试使用 Swift 解析以下 JSON 文件。我不知道如何解析没有对象的文件,所以任何帮助都会很棒。以下是 JSON 示例

[
    "sleeping bag",
    "Arabian camel, dromedary, Camelus dromedarius",
    "water"
]

我设置的解码文件的代码如下

struct ItemsStruct: Codable {
    let item: String
}

public extension Decodable{
    static func fromFile<T : Decodable>(_ filename : String, class : T.Type)->T?{
        let fileparts = filename.split(separator: ".")
        guard fileparts.count == 2 else{
            return nil
        }
        guard let path = Bundle.main.url(forResource: String(fileparts[0]), withExtension: String(fileparts[1])),
            let data = try? Data.init(contentsOf: path),
            let _struct = try? JSONDecoder().decode(T.self, from: data) else{
                return nil
        }
        return _struct
    }
}

guard let items = ItemsStruct.fromFile("objects.json", class: [ItemsStruct].self) else {return}
        for item in items{
            print(item)
        }

我知道我不应该有“let item: String”,但由于没有对象,我不确定要在结构中放入什么。

我需要不同的 JSON 数据吗?

【问题讨论】:

  • 有一个对象,一个数组...

标签: json swift parsing struct codable


【解决方案1】:

这是一个String的数组

guard let items = [String].fromFile("objects.json", class: [String].self) else {return}
for item in items{
    print(item)
}

顺便说一句,语法很奇怪。并且你应该让方法throw 交出所有可能的错误,而不是返回一个可选的并忽略所有错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多