0

With the following code I'm able to effectively get a JSON object, what I'm not sure how to do is retrieve the specific properties from the object.

Swift Code

@IBAction func testing(_ sender: Any) {
    let url = URL(string: "http://example.com/cars/mustang")

    let task = URLSession.shared.dataTask(with: url!) { data, response, error in
        guard error == nil else {
            print(error!)
            return
        }
        guard let data = data else {
            print("Data is empty")
            return
        }
        let json = try! JSONSerialization.jsonObject(with: data, options: [])
        print(json)
    }
    task.resume()
}

Here is what I see when I run the above code...

Output - JSON Object

(
    {
    color = "red";
    engine = "5.0";
    }
)

How can I get just the property color?

Thanks

rmaddy
  • 314,917
  • 42
  • 532
  • 579
fs_tigre
  • 10,650
  • 13
  • 73
  • 146
  • 3
    `json` is an array of dictionary. Access your data accordingly. – rmaddy Nov 12 '18 at 23:46
  • Hmm, I cannot figure it out. Can you please direct me to where I can find information on how to get items from an array of dictionaries in Swift? – fs_tigre Nov 13 '18 at 02:23
  • 2
    The [Collection Types](https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html) chapter of the Swift book is a good start. – rmaddy Nov 13 '18 at 02:24
  • 1
    Try this https://stackoverflow.com/questions/38743156/how-to-access-nested-json-in-brackets-in-swift – Alex Bailey Nov 13 '18 at 05:01
  • Please do not put the answer in your question. Either accept an answer below if it best helped or post your own showing your chosen solution. – rmaddy Nov 14 '18 at 00:27
  • @vadian Very good information, thanks. Quick question, based on your latest update on that answer, it looks like it's better to use `Codable` if using Swift 4, is this correct? If yes, the code posted by `Mohamed Mahdi Allani` below is a better approach than my solution. – fs_tigre Nov 14 '18 at 13:24

2 Answers2

2

Create a class which confirm the decodable protocol; CarInfo for example in your case

class CarInfo: Decodable

Create attributes of the class

var color: String

var engine: String

Create JSON key enum which inherits from CodingKey

enum CarInfoCodingKey: String, CodingKey {
   case color 
   case engine 
}

implement init

required init(from decoder: Decoder) throws

the class will be

class CarInfo: Decodable {
var color: String
var engine: String
enum CarInfoCodingKey: String, CodingKey {
case color
case engine
}
public init(from decoder: Decodabler) throws {
let container = try decoder.container(keyedBy: CarInfoCodingKey.self)
self.color = try container.decode(String.self, forKey: .color)
self.engine = try contaire.decode(String.self, forKey: .engine)
}
}

call decoder

let carinfo = try JsonDecoder().decode(CarInfo.self, from: jsonData)
  • Is this the simplest way to do it? – fs_tigre Nov 13 '18 at 02:18
  • 1
    @fs_tigre You only need one or two more lines in the code you posted in your question. Using this answer's solution is just a different solution over using `JSONSerialization`. – rmaddy Nov 13 '18 at 03:09
  • @rmaddy - Thank you for the clarification, I edited my original question with my solution. @-Mohamed Mahdi Allani - Thanks a lot for demonstrating other methods, I when with the simples approach. – fs_tigre Nov 13 '18 at 23:13
0

Here is how I did it...

@IBAction func testing(_ sender: Any) {
    let url = URL(string: "http://example.com/cars/mustang")

    let task = URLSession.shared.dataTask(with: url!) { data, response, error in
        guard error == nil else {
            print(error!)
            return
        }
        guard let data = data else {
            print("Data is empty")
            return
        }
        let json = try! JSONSerialization.jsonObject(with: data, options: [])

        guard let jsonArray = json as? [[String: String]] else {
            return
        }
        let mustangColor = jsonArray[0]["color"]

        print(mustangColor!)
    }
    task.resume()
}
fs_tigre
  • 10,650
  • 13
  • 73
  • 146