如何从API解码数组

时间:2019-04-09 19:42:25

标签: swift api

我从API得到以下响应:

[803442,1605299,1605300,1880804,1880806,1880808,1880810,1880811,1880817,1880819,1880820,1880825,1880826,1880828,1880829,1880830,1880831,1880832,1880833,1880834,1880835,1880836,1880844,1880847,1880849,1880850,1880851,1880862,1880863,1880864]

只是一个Int数组

我正尝试使用JSONDecoder对其进行解码,但由于它没有一个名称,这使我感到困惑。

如果我有这样的东西

{"results":[{"device_id":4085245,"locations":[{"time":1553285663,"lat":2.8019,"lon":-60.7276,"accuracy":80,"seq_number":722},{"time":1553328699,"lat":2.8025,"lon":-60.7266,"accuracy":14503,"seq_number":723}]}]}

我知道该怎么做,因为我可以构建这样的结构

struct results: Decodable {
    var device_id: Int
    var locations: [locations]
}
struct locations: Decodable {
    var time: Int
    var lat: Double
    var lon: Double
    var accuracy: Double
    var seq_number: Int
}

但是在第一种情况下,我不知道该怎么做。

请问有人有建议。

谢谢

2 个答案:

答案 0 :(得分:1)

template <size_t N> struct T<N, std::enable_if_t<(N>10), int>> { … }; 已经是Int,因此您可以轻松解码此类型的数组

Decodable

答案 1 :(得分:0)

它是Array中的Int。由于IntArray都已经Codable,因此您可以直接对其进行解码。游乐场示例:

import UIKit
import PlaygroundSupport

let data = "[803442, 1605299, 1605300, 1880804, 1880806, 1880808, 1880810, 1880811, 1880817, 1880819, 1880820, 1880825, 1880826, 1880828, 1880829, 1880830, 1880831, 1880832, 1880833, 1880834, 1880835, 1880836, 1880844, 1880847, 1880849, 1880850, 1880851, 1880862, 1880863, 1880864]".data(using: .utf8)!

if let decoded = try? JSONDecoder().decode([Int].self, from: data) {
   print(decoded)
}