-4

I'm a newbie to JSON. I've done a few readings but I'm still confused and I'm getting errors.

How do you parse the following data?

[{"symbol":"ALI","date":"1/22/2018","open":44.9000,"high":45.5000,"low":44.9000,"close":45.2000,"bid":45.1500,"ask":45.2000,"volume":6698800,"value":303245610.0000,"netForeign":-42279365.0000}]

I would like to get each string individually.

For instance: Symbol, Date, etc.

Any help would be greatly appreciated. Thanks!

As a reference, I tried the following solution but got an error: How to parse Json object in swift 3

9
  • where your code that you tried? Commented Feb 3, 2018 at 21:32
  • I'm voting to close this question as off-topic because no efforts were shown to solve the problem Commented Feb 3, 2018 at 21:32
  • Why? Vadian has answered my question. Kindly read. Commented Feb 3, 2018 at 21:37
  • thats not what i stated as the reason. Commented Feb 3, 2018 at 21:38
  • You just stated "because no efforts were shown to solve the problem". My problem was solved by Vadian. Commented Feb 3, 2018 at 21:43

1 Answer 1

5

In Swift 4 it's very straightforward with the Decodable protocol:

let jsonString = """
[{"symbol":"ALI","date":"1/22/2018","open":44.9000,"high":45.5000,"low":44.9000,"close":45.2000,"bid":45.1500,"ask":45.2000,"volume":6698800,"value":303245610.0000,"netForeign":-42279365.0000}]
"""

struct Item : Decodable {
    let symbol, date : String
    let open, high, low, close, bid, ask, value, netForeign : Double
    let volume : Int
}

do {
    let data = Data(jsonString.utf8)
    let result = try JSONDecoder().decode([Item].self, from: data)
    print(result)
} catch {
    print("error: ", error)
}

Or even with decoding the date string as Date

struct Item : Decodable {
    let symbol : String
    let date : Date
    let open, high, low, close, bid, ask, value, netForeign : Double
    let volume : Int
}

do {
    let data = Data(jsonString.utf8)
    let formatter = DateFormatter()
    formatter.dateFormat = "MM/dd/yyyy"
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .formatted(formatter)
    let result = try decoder.decode([Item].self, from: data)
    print(result)
} catch {
    print("error: ", error)
}

This is an example to put JSONDecoder and URLSession together:

let url = URL(string: "https://api.whatever...")!
URLSession.shared.dataTask(with:url) { (data, _, error) in
  if error != nil {
     print(error!)
  } else {
     do {
        let result = try JSONDecoder().decode([Item].self, from: data!)
        print(result)
    } catch {
        print("error: ", error)
    }
  }

}.resume()

Please learn to read JSON. It's pretty simple. There are only two collection types (array, dictionary) and four value types (string, number, bool and null). See also my answer in this question:

Sign up to request clarification or add additional context in comments.

10 Comments

Hi Vadian, thanks for the help! Sorry but I think I haven't made my question clear, but I am actually fetching the son file from the internet...
Use URLSession to get the data. There are hundreds of examples here on SO for example in the linked question. In this case omit the line let data = Data(jsonString.utf8) and use the data returned from the dataTask
Hi Vadian, I tried using the solution on the link you provided but I got the ff. error: Could not cast value of type '__NSArrayI' to 'NSDictionary'.
Do not use JSONSerialization. Pass the data to JSONDecoder in this answer.
Regarding your previous answer just now, how do I use the data returned from the dataTask? Sorry newbie here. I got the part let urlString = https://api.forecast.io/forecast/apiKey/37.5673776,122.048951 let url = URL(string: urlString) URLSession.shared.dataTask(with:url!) { (data, response, error) in if error != nil { print(error) } else { on my code, however, how do I put the value of the dataTask inside the do { let data=?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.