Handling incrementing JSON name using Swift

后端 未结 2 1611
既然无缘
既然无缘 2021-01-17 03:05

I have a JSON object with incrementing names to parse and I want to store the output into an object with a name field and a list of pet field. I normally use JSONDecoder as

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 03:35

    You can try this to parse your data as Dictionary. In this way, you can get all keys of the dictionary.

        let url = URL(string: "YOUR_URL_HERE")
        URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
            guard let data = data, error == nil else { return }
            do {
                let dics = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! Dictionary
                let keys = [String](dics.keys)
                print(keys) // You have the key list
                print(dics[keys[0]]) // this will print the first value
             } catch let error as NSError {
                print(error)
            }
        }).resume() 
    

    I hope you can figure out what you need to do.

提交回复
热议问题