Reputation:
Essentially I have the following function that responds to POST Request and displays JSON data.
I would like to just print the results of this data by printing the value of del_tex
At the top of the ViewController I define the variable structure as:
var structure = [NotesStructure]()
NotesStructure is the structure of the JSON received:
import UIKit
struct NotesStructure: Codable {
let del_tex: String
}
The following is the JSON function that fetches and processes the data. I try to print the value of del_tex but get the error that structure has no value del_tex
private func fetchJSON() {
guard let url = URL(string: "https://example.com/example/example"),
let value = driverName.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "person=\(driverName)&serial=\(peronNum)".data(using: .utf8)
URLSession.shared.dataTask(with: request) { data, _, error in
guard let data = data else { return }
do {
self.structure = try JSONDecoder().decode([NotesStructure].self,from:data)
DispatchQueue.main.async {
print(self.structure.del_tex)
}
}
catch {
print(error)
}
}.resume()
}
Upvotes: 0
Views: 50
Reputation: 51955
Your result is an array so you first need to access the array, either only the first element
do {
self.structure = try JSONDecoder().decode([NotesStructure].self,from:data)
if let first = self.structure.first {
print(first.del_tex)
}
...
or print the whole array
do {
self.structure = try JSONDecoder().decode([NotesStructure].self,from:data)
for item in self.structure {
print(item.del_tex)
}
...
Upvotes: 1