ios - Swift.DecodingError.Context(编码路径 :

标签 ios json swift url helper

我正在解码来自 URL repsonse 的 JSON(解码器)字符串,如下所示,并在解码过程中得到以下错误消息:

错误信息:

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "values", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "stat-list", intValue: nil), CodingKeys(stringValue: "stat", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "timestamps", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil))

这是我的响应中的 JSON 字符串:

{"values":[{"resourceId":"AAAAAA-3398-4280-8e32-BBBBBBBB","stat-list":{"stat":[{"timestamps":[1534186909854],"statKey":{"key":"cpu|underusedpercent"},"data":[25.0]},{"timestamps":[1538430850296],"statKey":{"key":"mem|consumedPct"},"data":[99.9984130859375]}]}}]}

我适合的结构:

struct VrOpsObjectCpuRAMStatistics: Decodable
{
    struct Values: Decodable
    {
        let resourceId: String
        struct StatList: Decodable
        {
            struct Stat: Decodable
            {
                let timestamps: [String] 
                struct StatKey: Decodable
                {
                    let key: String
                }
                let statKey: StatKey
                let data: [String] 
            }
            let stat: [Stat]
        }
        let statList: StatList
        private enum CodingKeys: String, CodingKey
        {
            case resourceId
            case statList = "stat-list"
        }
    }
    let values: [Values]
}

我使用 JSON 解码器的解码调用:

 self.vrOpsObjectCpuRamStatistics = try JSONDecoder().decode(VrOpsObjectCpuRAMStatistics.self , from: jsonData)
                    if self.vrOpsObjectCpuRamStatistics != nil
                    {
                        print("Data from REST call has been converted sucessfully to JSON Object" );
                        return (true, self.vrOpsObjectCpuRamStatistics);
                    }
                    else
                    {
                        return (false, "Decoding vRops data to JSON object has been failed!");
                    }

最佳答案

你有这个错误是因为,你尝试将时间戳解码为字符串数组,但你在 JSON 中有整数数组

关于ios - Swift.DecodingError.Context(编码路径 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52599547/

相关文章:

ios - 我可以用来提交到应用商店的 Xcode 的最低版本是多少(截至 2015 年 10 月)

ios - UICollectionView 是否随着 Xcode 7、swift 2.0 更改了协议(protocol)?

json - postman - 如何发送具有不同参数值的相同请求

json - 删除 key :value from an JSON object using jq

ios - 如何确保 WidgetKit View 显示来自 @FetchRequest 的正确结果?

ios - 当 UIView 用键盘向上滚动时,它似乎笨拙地在每个文本字段上跳跃,不知道如何修复它

iphone - 在图库中显示一些缩放图像

ios - 如何在另一个 React 组件中正确使用 TabNavigator

ajax - 当我访问 Tickets.com json api 时,未捕获语法错误 : Unexpected token : ,

Swift:使用 CocoaPods 时无法构建 Objective-C 模块