从 API 中以编程方式创建 JSON 数据导致 Swift
Create JSON data programmatically from API results in Swift
我正在使用以下 json 负载向 API 发出请求:
var json: [String: Any] = [
"locations": [
[
"latitude" : 10,
"longitude": 10,
],
[
"latitude" : 20,
"longitude": 20,
]
]
]
现在,上面的 json 是硬编码的,所以我可以测试 API 的响应。有问题的 API returns 海拔数据。
但是,我遇到的问题是我不想对 json 有效负载进行硬编码,我需要使用从单独的 API 获得的其他数据填充 json这为我提供了 lat/lon 坐标。
如何使用从单独的 API 检索到的 lat/lon 结果填充 json?
创建 Encodable
为 JSON 建模的结构:
struct Locations: Encodable {
let locations: [Location]
}
struct Location: Encodable {
let latitude: Double
let longitude: Double
}
let locations = Locations(locations: [
Location(latitude: 10, longitude: 10),
Location(latitude: 40, longitude: 40)
])
do {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(locations)
// use `data` as the payload to send to your server
print(String(bytes: data, encoding: .utf8)!)
} catch {
print(error)
}
我正在使用以下 json 负载向 API 发出请求:
var json: [String: Any] = [
"locations": [
[
"latitude" : 10,
"longitude": 10,
],
[
"latitude" : 20,
"longitude": 20,
]
]
]
现在,上面的 json 是硬编码的,所以我可以测试 API 的响应。有问题的 API returns 海拔数据。
但是,我遇到的问题是我不想对 json 有效负载进行硬编码,我需要使用从单独的 API 获得的其他数据填充 json这为我提供了 lat/lon 坐标。
如何使用从单独的 API 检索到的 lat/lon 结果填充 json?
创建 Encodable
为 JSON 建模的结构:
struct Locations: Encodable {
let locations: [Location]
}
struct Location: Encodable {
let latitude: Double
let longitude: Double
}
let locations = Locations(locations: [
Location(latitude: 10, longitude: 10),
Location(latitude: 40, longitude: 40)
])
do {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(locations)
// use `data` as the payload to send to your server
print(String(bytes: data, encoding: .utf8)!)
} catch {
print(error)
}