Chris Mikkelsen Chris Mikkelsen - 3 months ago 12
JSON Question

How To Parse JSON with SwiftyJson

This is the data

[{
"mineral": "Phosphorus",
"data": [ 7.65, 19.74, 15.48 ]
},

{
"mineral": "Calcium",
"data": [ 1.65, 1.32, 1.78 ]
}]


And this is the code I used to parse it.

if let dataFromString = self.response.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {

let json = JSON(data: dataFromString)

var valuesB = [Double]()

for i in 0..<json.count {
self.nutrient.append(json[i]["mineral"].stringValue)
print("Nutrient: \(json[i]["mineral"].stringValue)\n")

for j in 0..<json[i]["data"].count {
valuesB.append(json[i]["data"][j].doubleValue)
print("Values: \(json[i]["data"][j].doubleValue)")
}

values.append(valuesB)
}
}


But All I get is

Nutrient: Phosphorus

Values: 0.0
Values: 0.0
Values: 0.0

Nutrient: Calcium

Values: 0.0
Values: 0.0
Values: 0.0


I was using SwiftyJson for Xcode 7 with Swift, is there another way around this using SwiftyJson?

Answer

You're missing the conversion of the JSON to a JSON array using the Optional getters of SwiftyJSON and the JSON it's not interpreted as an array properly, so you need to use it like in the following code:

let jsonString = "[{\"mineral\": \"Phosphorus\",\"data\": [ 7.65, 19.74, 15.48 ]},{\"mineral\": \"Calcium\", \"data\": [ 1.65, 1.32, 1.78 ]}]"

if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
        let json = JSON(data: dataFromString)

        // Check if the JSON is an array otherwise nil 
        if let jsonArray = json.array {

            var valuesB = [Double]()

            for i in 0..<jsonArray.count {
                print(jsonArray[i]["mineral"].stringValue)
                print("Nutrient: \(json[i]["mineral"].stringValue)\n")

                for j in 0..<jsonArray[i]["data"].count {
                    valuesB.append(jsonArray[i]["data"][j].doubleValue)
                    print("Values: \(jsonArray[i]["data"][j].doubleValue)")
                }
            }
        }
    }

And you should see in the console:

Phosphorus
Nutrient: Phosphorus

Values: 7.65
Values: 19.74
Values: 15.48
Calcium
Nutrient: Calcium

Values: 1.65
Values: 1.32
Values: 1.78

I hope this help you.