apollo-ios: Error decoding Array while using custom scalars in iOS swift

Apollo graphQL doesn’t convert json array.

I have schema as show below. Here question_r is an array of dictionaries received as Json. I am facing issue converting it. Is there any way i can successfully decode it?

This is the error: couldNotConvert(value: <__NSSingleObjectArrayI … to: Swift.Dictionary<Swift.String, Swift.Optional<Any>>)"

This is the response in playground:

"questionR": [
                              {
                                "identifier": "123",
                                "skills": {
                                  "primary_skill": "vocabulary",
                                  "secondary_skill": "reading",
                                }
                              }
                            ]
**This is the schema.json**
 {
            "name": "question_r",
            "description": "",
            "args": [],
            "type": {
              "kind": "SCALAR",
              "name": "Json",
              "ofType": null
            },
            "isDeprecated": false,
            "deprecationReason": null
          }

My script looks like this:

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

I was able to get custom scalars working for dictionary but not array using this issue link:

[Link]https://github.com/apollographql/apollo-ios/issues/36

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 19 (9 by maintainers)

Most upvoted comments

OK, gave this a think and representing it as an enum should at least help a bit in terms of being able to stay kiiiinda type safe:

public typealias Json = JSONType
public enum JSONType: JSONDecodable {
    case dictionary([String: Any])
    case array([Any])
    
    public init(jsonValue value: JSONValue) throws {
        switch value {
        case let dictionary as [String: Any]:
            self = .dictionary(dictionary)
        case let array as [Any]:
            self = .array(array)
        default:
            throw JSONDecodingError.couldNotConvert(value: value, to: JSONType.self)
        }
    }
}


func whatAmI(_ json: JSONType) {
    switch json {
    case .array(let array):
        print("Array: \(array)")
    case .dictionary(let dictionary):
        print("Dictionary: \(dictionary)")
    }
}

let first = try JSONType(jsonValue: ["first item", "second item"])
whatAmI(first)
// prints "Array: ["first item", "second item"]"

let second = try JSONType(jsonValue: [ "key" : "value" ])
whatAmI(second)
// prints "Dictionary: ["key": "value"]"

I’ve definitely got some things I want to be able to add if we can get things annotated locally long term, but that’s unfortunately part of the codegen stuff which is taking me forever 😭