Hello all:
I am getting JSON data from a URL and then putting it into an array, and then I need to get that data into an array of objects. Here is the struct and array (actual names hidden for confidentiality):
struct sTest: Codable
{
var a: String
var b: String
var c: String
var d: String
var e: String
var f: String
var g: String
}
var sTestArray = [sTest]()
and I get the data from the URL using this code snippet
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
{
let theList: NSArray = jsonObj["data"] as! NSArray
and when I print the array in the Console, this is what I get:
Success
{
data = (
{
a = "a value";
b = "b value";
c = "c value";
d = "d value";
e = "e value";
f = "f value";
g = "g value";
},
and there are 144 data elements.
I am stuck on parsing this into the sTestArray. I have tried setting up a decoder, and also tried using array indexes, but no joy. Can anyone offer any assistance?
Thanks in advance!
John.
Assuming your JSON text looks like this:
{
data: [
{
"a" : "a value1",
"b" : "b value1",
"c" : "c value1",
"d" : "d value1",
"e" : "e value1",
"f" : "f value1",
"g" : "g value1"
},
{
"a" : "a value144",
"b" : "b value144",
"c" : "c value144",
"d" : "d value144",
"e" : "e value144",
"f" : "f value144",
"g" : "g value144"
}
]
}
You may need to prepare two structs:
struct Result: Codable {
var data: [STest]
}
struct STest: Codable {
var a: String
var b: String
var c: String
var d: String
var e: String
var f: String
var g: String
}
When you successfully prepare your structs, you can decode it like this:
guard let data = data else {
print("data invalid")
return
}
do {
let result = try JSONDecoder().decode(Result.self, from: data)
let theList = result.data
//Use `theList` here
print(theList)
//...
} catch {
print(error)
}