Apollo iOS将JSONArray转换为String

时间:2019-03-04 05:48:07

标签: ios swift apollo

如果您的架构中没有对象映射,则Apollo iOS Swift不会将JSONArray转换为String。 我有一个查询,其中对象的结果数组未在schema.json中映射 模式中的描述:

{"name":"stack",
"description":"",
"args":[
],
"type":{
"kind":"LIST",
"name":null,
"ofType":{
"kind":"SCALAR",
"name":"JSON",
"ofType":null
}}}

接收到的数据如下:

"stack":[{ 
"name":"React",
"version":"",
"category":[ "JavaScript Frameworks"]}]

我收到的错误消息是

[Apollo.GraphQLResultError(path: ["userHost", "stack"], underlying: Apollo.JSONDecodingError.couldNotConvert(value: {
    category =     (
        React
    );
    name = "JavaScript Frameworks";
    version = "";
}, to: Swift.String))]

1 个答案:

答案 0 :(得分:0)

我只能通过更改JSONStandardTypeConversions文件来解决此问题。 是:

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

    public var jsonValue: JSONValue {
        return self
    }
}

我将其更改为

    extension String: JSONDecodable, JSONEncodable {
      public init(jsonValue value: JSONValue) throws {

        let string = value as? String

        if (string == nil) {
            do {
                let data1 =  try JSONSerialization.data(withJSONObject: value, options: JSONSerialization.WritingOptions.prettyPrinted) // first of all convert json to the data
                let convertedString = String(data: data1, encoding: String.Encoding.utf8) // the data will be converted to the string
                if (convertedString == nil) {
                    throw JSONDecodingError.couldNotConvert(value: value, to: String.self)
                } else {
                    self = convertedString ?? ""
                }
            } catch let myJSONError {
                print(myJSONError)
                throw JSONDecodingError.couldNotConvert(value: value, to: String.self)
            }
        } else {
            self = string ?? ""
        }
      } 
public var jsonValue: JSONValue {
    return self
  }
}

如果标准转换为String不起作用,我将强制将JSON对象转换为String。这样,我至少可以获得一些数据。