将SAPOData.EntityValue的数组编码/解码到CompositeStorage

时间:2018-04-04 00:24:35

标签: ios swift sap

我正在使用适用于iOS的SAP Cloud Platform SDK,尝试弄清楚如何将EntityValue数组放入CompositeStorage,并将其取出。我收到错误:

  

typeMismatch(Swift.Dictionary,Swift.DecodingError.Context(codingPath:[Foundation。(_ PlistKey in _5692656F4C05BA2A580AE9322E9FB0A6)(stringValue:" Index 0",intValue:Optional(0)),Foundation。(_ PlistKey in _5692656F4C05BA2A580AE9322E9FB0A6)(stringValue:"索引0",intValue:可选(0))],debugDescription:"预计解码字典但找到了__NSCFData。",underlyingError:nil))

我试图从CompositeStore获取值:

var entities: [ExpensereportType] {
    do {
        guard let results = try Cache.shared.store.get(Array<ExpensereportType>.self, for: CollectionType.expensereport.rawValue) else {
            return []
        }
        return results
    }
    catch {
        print(error)
        return []
    }
}

他们正在编码:

self.service.fetchReservation(matching: query) { result, error in
    guard let result = result else { return completionHandler(error!) }

    do {
        let encodedResult = try JSONEncoder().encode(result)
        try self.store.put(encodedResult, for: CollectionType.reservation.rawValue)
    }
    catch {
        completionHandler(error)
    }
    completionHandler(nil)
}

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这个问题的解决方案很有意思:事实证明JSONEncoder非常聪明,可以按原样处理 Array<EntityValue>,或者单个项目是地图编码。但是,JSONDecoder会自动处理顶级数组项,您可以对项进行映射解码。

工作解决方案:

// MARK: - Encode
self.service.fetchReservation(matching: query) { result, error in
        guard let result = result else {
            completionHandler(error!)
            return
        }

        do {
            let encodedResult = try JSONEncoder().encode(result)
            // try result.map { try JSONEncoder().encode($0) }   ALSO VALID
            try self.store.put(encodedResult, for: CollectionType.expensereport.rawValue)
        }
//...

// MARK: - Decode `Array<ExpensereportType>`
guard let results = try Cache.shared.store.get(Array<ExpensereportType>.self, for: CollectionType.expensereport.rawValue) else {
    return []
}
let decoder = JSONDecoder()
decoder.userInfo.updateValue(myDataService.metadata, forKey: CSDLDocument.csdlInfoKey)
return try results.map { try decoder.decode(ExpensereportType.self, from: $0)}