-1

i have JSON object like below

{
"a":"123",
"b":"testing"
}

In java i am using JSONObject.names() method.

JSONArray keys = jsonObject.names();

And result getting like this ["a","b"];

Similar result how to get in swift?

Thanks.

cj devin
  • 1,045
  • 3
  • 13
  • 48

2 Answers2

2

You can use JSONSerialization to parse the JSON data into a Dictionary of type [String:Any] and then use keys to get all the key strings from it.

do {
    if let dict = try JSONSerialization.jsonObject(with: data) as? [String:Any] {
        print(dict.keys)
    }
} catch {
    print(error)
}
PGDev
  • 23,751
  • 6
  • 34
  • 88
1
var results = [String:Array<DataModel>]

where,

class DataModel {
    var name: String?     
}

and to fetch the keys and value,

for i in 0...(results.length-1){
    // To print the results keys
    print(results.keys[results.startIndex.advancedBy(i)])
    // To get value from that key
    let valueFromKeyCount = (results[results.keys[results.startIndex.advancedBy(i)]] as Array<DataModel>).count
    for j in 0...(valueFromKeyCount-1) {
         let dm = results[results.keys[results.startIndex.advancedBy(i)]][j] as DataModel
         print(dm.name) 
    }
}

Your question is already answered here - How to fetch the key from JSON in Swift?

teja_D
  • 383
  • 3
  • 18