簡體   English   中英

在Swift 4中解碼沒有鍵的JSON

[英]Decoding a JSON without keys in Swift 4

我正在使用一個返回這個非常可怕的JSON的API:

[
  "A string",
  [
    "A string",
    "A string",
    "A string",
    "A string",
    …
  ]
]

我正在嘗試使用JSONDecoder解碼嵌套數組,但它沒有單個鍵,我真的不知道從哪里開始......你有什么想法嗎?

非常感謝!

如果結構保持不變,則可以使用此Decodable方法。

首先創建一個可解碼的模型,如下所示:

struct MyModel: Decodable {
    let firstString: String
    let stringArray: [String]

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        firstString = try container.decode(String.self)
        stringArray = try container.decode([String].self)
    }
}

或者如果你真的想保留JSON的結構,就像這樣:

struct MyModel: Decodable {
    let array: [Any]

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        let firstString = try container.decode(String.self)
        let stringArray = try container.decode([String].self)
        array = [firstString, stringArray]
    }
}

並像這樣使用它

let jsonString = """
["A string1", ["A string2", "A string3", "A string4", "A string5"]]
"""
if let jsonData = jsonString.data(using: .utf8) {
    let myModel = try? JSONDecoder().decode(MyModel.self, from: jsonData)
}

這對於解碼來說有點有趣。

你沒有任何key 因此它消除了對包裝器struct的需要。

但看看內在的類型。 你得到String[String]類型的混合。 所以你需要處理這種混合類型的東西。 你需要一個精確的enum

// I've provided the Encodable & Decodable both with Codable for clarity. You obviously can omit the implementation for Encodable
enum StringOrArrayType: Codable {
    case string(String)
    case array([String])

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        do {
            self = try .string(container.decode(String.self))
        } catch DecodingError.typeMismatch {
            do {
                self = try .array(container.decode([String].self))
            } catch DecodingError.typeMismatch {
                throw DecodingError.typeMismatch(StringOrArrayType.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Encoded payload conflicts with expected type"))
            }
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .string(let string):
            try container.encode(string)
        case .array(let array):
            try container.encode(array)
        }
    }
}

解碼過程:

let json = """
[
  "A string",
  [
    "A string",
    "A string",
    "A string",
    "A string"
  ]
]
""".data(using: .utf8)!

do {
    let response = try JSONDecoder().decode([StringOrArrayType].self, from: json)
    // Here, you have your Array
    print(response) // ["A string", ["A string", "A string", "A string", "A string"]]

    // If you want to get elements from this Array, you might do something like below
    response.forEach({ (element) in
        if case .string(let string) = element {
            print(string) // "A string"
        }
        if case .array(let array) = element {
            print(array) // ["A string", "A string", "A string", "A string"]
        }
    })
} catch {
    print(error)
}

一個可能的解決方案是使用JSONSerialization ,然后你可能只是在這樣的json中挖掘,這樣做:

import Foundation

let jsonString = "[\"A string\",[\"A string\",\"A string\", \"A string\", \"A string\"]]"
if let jsonData = jsonString.data(using: .utf8) {
    if let jsonArray = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [Any] {
        jsonArray.forEach {
            if let innerArray = $0 as? [Any] {
                print(innerArray) // this is the stuff you need
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM