【问题标题】:Apollo iOS convert JSONArray to StringApollo iOS 将 JSONArray 转换为 String
【发布时间】:2019-07-25 09:56:52
【问题描述】:

如果架构中没有对象映射,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))]

【问题讨论】:

    标签: ios swift apollo


    【解决方案1】:

    我只能通过更改 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
      }
    }
    

    如果标准转换为字符串不起作用,我将强制将 JSON 对象转换为字符串。这样,我至少得到了一些数据。

    【讨论】:

    • 我也遇到了这个 JSONArray 到字符串的问题,我在我的 JSONStandardTypeConversions 文件中应用了这个更改,但仍然是同样的错误。 couldNotConvert(value: <__NSArrayI 0x281834330> to Swift.String。你能指导一下其他方式吗
    猜你喜欢
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    相关资源
    最近更新 更多