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?
"questionR": [
{
"identifier": "123",
"skills": {
"primary_skill": "vocabulary",
"secondary_skill": "reading",
}
}
]
This is the schema
{
"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
This is the typealias where i am defining Json. It can ve dictionary or array of dictionary
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
}
}
Any workaround for this? Am i missing something here?
I got it working by assuming Json to be an array and converting a dictionary to array.
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
}
}
This works for me.