Parsing JSON and Custom Scalar problems- SWIFT iOS

Hi apollo graphql, I am trying to parse a custom scalar with the type JSON, i used --passthroughCustomScalars, and had success in parsing a DICTIONARY, by using a decoder.

But now with a few updates by our server, the JSON type now can be a Dictionary, or an Array of dictionary. I tried using the code from the documentation:

enum CustomJSON {
case dictionary([String: Any])
case array([Any])
}

extension JSON: JSONDecodable {
init(jsonValue value: JSONValue) throws {
if let dict = value as? [String: Any] {
self = .dictionary(dict)
} else if let array = value as? [Any] {
self = .array(array)
} else {
throw JSONDecodingError.couldNotConvert(value: value, to: JSON.self)
}
}
}

No problem in compiling, but can you help me on how would I use the response from the server…
I cant seem to cast a JSON data type to an array or dictionary.

Hi @carmelitodeveloper!

So you’d need to switch on CustomJSON to determine which type it is:

switch yourObject.customJSONProperty {
case .dictionary(let dictionary):
    // Do stuff with `dictionary`
case .array(let array): 
   // Do stuff with `array`
}

Does that help?

1 Like

Hi @designatednerd,

That was very helpful thank you! i feel i forgot how enums worked.
can you help with another concern, with the CustomJSON implemented, how would i use it when passing data to the server, with a parameter using the same custom JSON scalar… can be a dictionary, or an array.

Im currently getting “Type of expression is ambiguous without more context”

Hey I’m sorry I missed this earlier - you need to make sure that if your Custom Scalar is named JSON you use that name instead of CustomJSON in order to declare your enum and extension - otherwise the compiler won’t have any idea what that JSON type is.