解码没有属性名的JSON数组



我已经通过其他线程关于试图解析JSON数据的JSON数组没有名称。从我发现你需要使用一个unkeyedContainer,但我不完全确定从我已经看到的例子,这是如何与数据模型的工作。

下面是来自open charge api的数据片段:

[
{
"IsRecentlyVerified": false,
"ID": 136888,
"UUID": "254B0B07-E7FC-4B4B-A37C-899BCB9D7261",
"DataProviderID": 18,
"DataProvidersReference": "0a9fdbb17feb6ccb7ec405cfb85222c4",
"OperatorID": 3,
"UsageTypeID": 1,
"AddressInfo": {
"ID": 137234,
"Title": "Ballee Road Park & Share",
"AddressLine1": "Ballee Road",
"Town": "Ballymena",
"Postcode": "BT42 2HD",
"CountryID": 1,
"Latitude": 54.844648,
"Longitude": -6.273606,
"AccessComments": "Ballee Road Park and Share, Ballymena",
"RelatedURL": "http://pod-point.com",
"Distance": 3.81818421833416,
"DistanceUnit": 2
},
"Connections": [
{
"ID": 191571,
"ConnectionTypeID": 25,
"Reference": "1",
"StatusTypeID": 50,
"LevelID": 2,
"Amps": 32,
"Voltage": 400,
"PowerKW": 22,
"CurrentTypeID": 20
},

在我看来,第一个[和{没有属性名,我认为这是在xcode中创建错误:" error !: typeMismatch (Swift.Dictionary<迅速。字符串,任意>Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String,>但是发现了一个数组。",底层错误:nil))">

下面是我的数据模型:

import Foundation
struct PublicCharger: Decodable {
let AddressInfo: [AddressInfo]
}
下面是我的代码:
//Find public chargers from local coordinates
func findPublicChargers(lat: Double, long: Double) {
//Use apiurl to pull all charge points that are currently in that area by adding lat and long into the api call &latitude=***&longitude=*****
let apiurl = "https://api.openchargemap.io/v3/poi/?output=json&countrycode=UK&maxresults=100&compact=true&verbose=false"
let urlString = "(apiurl)&latitude=(lat)&longitude=(long)"
//print(urlString)
performRequest(urlString: urlString)

}

//Perform API Request - (London App Brewry code)
//Create the custom url

func performRequest(urlString: String) {
if let url = URL(string: urlString) {
//print("Called")
//Create a URL Session
let session = URLSession(configuration: .default)
//Give the session a task
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
return
}
if let safeData = data {
//let dataString = String(data: safeData, encoding: .utf8)
//print(dataString)
self.parseJSON(data: safeData)
print("Data: (safeData)")
}
}
//Start the task
task.resume()
}
}

func parseJSON(data: Data){
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(PublicCharger.self, from: data)
print("Data: (decodedData.AddressInfo[0].Title)")
} catch {
print("Error!: (error)")
}
}

struct AddressInfo: Decodable {
let Title: String
}

我已经看到,在数据模型中,您需要包含一个无键的容器元素。我只是不确定这应该如何在数据模型中执行。

如果您能对此有所了解,我将不胜感激。

尝试将PublicCharger数据模型更改为

struct PublicCharger: Decodable {
let AddressInfo: [AddressInfo]
}

和你的parseJSON函数

func parseJSON(data: Data){
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode([PublicCharger].self, from: data)
if !decodedData.isEmpty {
print("Data: (decodedData[0].AddressInfo[0].Title)")
} else {
print("Empty result!")
}
} catch {
print("Error!: (error)")
}
}

最新更新