Reputation: 99
All the examples I find are using dictionary types, for example: user: x, book: y
but how can I convert this type of Json which doesn't contain a key?
["1","137","56","56"]
This is of type String?
I tried:
struct Candidate: Decodable {
var S: String?
}
let chainsAllowed = ["1","137","56","56"]
let jsonObjectData = chainsAllowed.data(using: .utf8)!
let candidate = try? JSONDecoder().decode(
Candidate.self,
from: jsonObjectData
)
but I get nil. How can I convert it into an array?
Thanks
Upvotes: 2
Views: 112
Reputation: 879
Do this:
import Foundation
let chainsAllowed = #"["1","137","56","56"]"#
let jsonObjectData = chainsAllowed.data(using: .utf8)
let candidate = try? JSONDecoder().decode(
[String].self,
from: jsonObjectData!
)
print(candidate!)
Output:
["1", "137", "56", "56"]
For your information: An array is actually perfectly valid JSON. In fact, a JSON text can be any of
false / null / true / object / array / number / string
. See https://datatracker.ietf.org/doc/html/rfc8259#section-2
Upvotes: 4