1

我有如下所示的架构。这里 question_r 是作为 Json 接收的字典数组。我面临转换它的问题。有什么办法可以成功解码吗?

"questionR": [
                              {
                                "identifier": "123",
                                "skills": {
                                  "primary_skill": "vocabulary",
                                  "secondary_skill": "reading",
                                }
                              }
                            ]

这是架构

{
            "name": "question_r",
            "description": "",
            "args": [],
            "type": {
              "kind": "SCALAR",
              "name": "Json",
              "ofType": null
            },
            "isDeprecated": false,
            "deprecationReason": null
          }
}

我的脚本如下所示:

SCRIPT_PATH="${PODS_ROOT}/Apollo/scripts" cd "${SRCROOT}/${TARGET_NAME}" "${SCRIPT_PATH}"/run-bundled-codegen.sh codegen:generate --target=swift --includes= ./**/*.graphql --passthroughCustomScalars --localSchemaFile="schema.json" API.swift

这是我定义 Json 的类型别名。它可以是字典或字典数组

public typealias Json = [String:Any?]

extension Dictionary: JSONDecodable {
    public init(jsonValue value: JSONValue) throws {
        guard let dictionary = value as? Dictionary else {
            throw JSONDecodingError.couldNotConvert(value: value, to: Dictionary.self)
        }
        self = dictionary
    }
}

extension Array: JSONDecodable{
    public init(jsonValue value: JSONValue) throws {
        guard let array = value as? Array else {throw JSONDecodingError.couldNotConvert(value: value, to: Array.self)}
        self = array
    }
}

有什么解决方法吗?我在这里错过了什么吗?

4

1 回答 1

1

我通过假设 Json 是一个数组并将字典转换为数组来让它工作。

public typealias Json = [[String:Any?]]

extension Json: JSONDecodable{
 
    public init(jsonValue value: JSONValue) throws{
        guard let array = value as? Array else {
            guard let dict = value as? Dictionary<String, Any> else { throw JSONDecodingError.couldNotConvert(value: value, to: Dictionary<String, Any>.self)
            }
            self = .init(arrayLiteral: dict)
            return
        }
        self = array
    }
}

这对我有用。

于 2020-11-23T09:22:05.657 回答