Mayday Mayday -4 years ago 173
JSON Question

Using SwiftyJSON for subarray with Swift 3.1

I have a json data. I never use SwiftyJSON before. I am trying first time.

My json like this:

[
{
"Id": 1,
"Name": "A",
"SubNames": [
{
"SubId": 1,
"SubName": "A1"
},
{
"SubId": 2,
"SubName": "A2"
}]
},
{
"Id": 2,
"Name": "B",
"SubNames": [
{
"SubId": 1,
"SubName": "B1"
},
{
"SubId": 2,
"SubName": "B2"
}]
}
]


I can handle Name and append a array. But I can't handle SubNames. I tried somethings but doesn't work unfortunately. I want to append SubNames a array. This array will be like this:

[["A1","A2"],["B1","B2"]]


I use this code:

let json = JSON(data: data!)
for (_,subJson):(String, JSON) in json {
self.names.append(subJson["Name"].stringValue
}

Answer Source

try this to access those fields, and you shouldn't do data! here

guard let `data` = data else {
    //no data handling
    return 
}
let dataArray = JSON(data: data).arrayValue
var arrayOfAllSubnames: [[String]] = [[]]

for object in dataArray {
    var arrayOfSubnames: [String] = []
    if let subnames = object["SubNames"].array {
        for subname in subnames {
            //here you get `"SubId": 2, "SubName": "B2"` object
            let subnameValue = subname["SubName"].stringValue
            arrayOfSubnames.append(subnameValue)
        }
    }
    arrayOfAllSubnames.append(arrayOfSubnames.append)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download