How can I print this JSON value in Swift 5? - json

{
"optionChain": {
"result": [
{
"underlyingSymbol": "AAPL",
"expirationDates": [
1606435200,
1607040000,
1607644800,
1608249600,
1608768000,
1609372800,
1610668800,
1613692800,
1616112000,
1618531200,
1623974400,
1626393600,
1631836800,
1642723200,
1655424000,
1663286400,
1674172800
],
"strikes": [
55,
60,
65,
70,
75
],
"hasMiniOptions": false,
How can I print out "underlyingSymbol" or any of those related fields in JSON? I understand printing out a single JSON field, but how do I get into the embedded ones?
So I made the Decodable as Suggested below:
struct Something: Decodable
{
let optionChain: OptionChain
let error: String
}
struct OptionChain: Decodable
{
let result: [ResultElement]
}
struct ResultElement: Decodable
{
let underlyingSymbol: String
let expirationDates: [Int]
let strikes: [Int]
let hasMiniOptions: Bool
let quote: [quoteElement]
let options: [optionsElement]
}
struct quoteElement: Decodable
{
let language: String
let region: String
let quoteType: String
let quoteSourceName: String
let triggerable: Bool
let currency: String
let firstTradeDateMilliseconds: Int
let priceHint: Int
let regularMarketChange: Int
let regularMarketChangePercent: Int
let regularMarketTime: Int
let regularMarketPrice: Int
let regularMarketDayHigh: Int
let regularMarketDayRange: String
let regularMarketDayLow: Int
let regularMarketVolume: Int
let regularMarketPreviousClose: Int
let bid: Int
let ask: Int
let bidSize: Int
let askSize: Int
let fullExchangeName: String
let financialCurrency: String
let regularMarketOpen: Int
let averageDailyVolume3Month: Int
let averageDailyVolume10Day: Int
let fiftyTwoWeekLowChange: Int
let fiftyTwoWeekLowChangePercent: Int
let fiftyTwoWeekRange: String
let fiftyTwoWeekHighChange: Int
let fiftyTwoWeekHighChangePercent: Int
let fiftyTwoWeekLow: Int
let fiftyTwoWeekHigh: Int
let dividendDate: Int
let earningsTimestamp: Int
let earningsTimestampStart: Int
let earningsTimestampEnd: Int
let trailingAnnualDividendRate: Int
let trailingPE: Int
let trailingAnnualDividendYield: Int
let epsTrailingTwelveMonths: Int
let epsForward: Int
let epsCurrentYear: Int
let priceEpsCurrentYear: Int
let sharesOutstanding: Int
let bookValue: Int
let fiftyDayAverage: Int
let fiftyDayAverageChange: Int
let fiftyDayAverageChangePercent: Int
let twoHundredDayAverage: Int
let twoHundredDayAverageChange: Int
let twoHundredDayAverageChangePercent: Int
let marketCap: Int
let forwardPE: Int
let priceToBook: Int
let sourceInterval: Int
let exchangeDataDelayedBy: Int
let tradeable: Bool
let exchange: String
let shortName: String
let longName: String
let marketState: String
let messageBoardId: String
let exchangeTimezoneName: String
let exchangeTimezoneShortName: String
let gmtOffSetMilliseconds: Int
let market: String
let esgPopulated: Bool
let displayName: String
let symbol: String
}
struct optionsElement: Decodable
{
let expirationDate: Int
let hasMiniOptions: Bool
let calls: [callPutElement]
let puts: [callPutElement]
}
struct callPutElement: Decodable
{
let contractSymbol: String
let strike: Int
let currency: String
let lastPrice: Int
let change: Int
let percentChange: Int
let volume: Int
let openInterest: Int
let bid: Int
let ask: Int
let contractSize: String
let expiration: Int
let lastTradeDate: Int
let impliedVolatility: Int
let inTheMoney: Bool
}
However now I am receiving an error:
JSONSerialization error: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in object around character 1." UserInfo={NSDebugDescription=No string key for value in object around character 1.})))

I'd use the Codable apis:
struct Something: Decodable {
let optionChain: OptionChain
}
struct OptionChain: Decodable {
let result: [ResultElement]
}
struct ResultElement: Decodable {
let underlyingSymbol: String
let expirationDates: [Int]
let strikes: [Int]
let hasMiniOptions: Bool
}
let jsonString = "{...}"
let jsonData = jsonString.data(using: .utf8)!
let decoder = JSONDecoder()
let something = try decoder.decode(Something.self, from: jsonData)
print(something.optionChain.result.map { $0.underlyingSymbol })

Related

API Decoding Struct Swift

Hello I'm trying to decode this API, https://gorest.co.in/public-api/posts. What I'm doing wrong with structs? Thank you.
struct Root: Decodable {
let first: [Code]
let second: [Meta]
let third: [Post] }
struct Code: Decodable {
let code: Int
}
struct Meta: Decodable {
let meta: [Pagination]
}
struct Pagination: Decodable {
let total: Int
let pages: Int
let page: Int
let limit: Int
}
struct Post: Decodable {
let id: Int
let user_id: Int
let title: String
let body: String
}
Quicktype.io is your friend. Post the JSON to it and get the struct back automatically.
// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let root = try? newJSONDecoder().decode(Root.self, from: jsonData)
import Foundation
// MARK: - Root
struct Root: Codable {
let code: Int
let meta: Meta
let data: [Datum]
}
// MARK: - Datum
struct Datum: Codable {
let id, userID: Int
let title, body: String
enum CodingKeys: String, CodingKey {
case id
case userID = "user_id"
case title, body
}
}
// MARK: - Meta
struct Meta: Codable {
let pagination: Pagination
}
// MARK: - Pagination
struct Pagination: Codable {
let total, pages, page, limit: Int
}

OpenWeatherMap and Swift 4

I am trying to build a simple weather app using OpenWeatherMap APIs in Swift 4.
I can parse Json data in simple cases, but this one has a more complex structure.
This is the Json file the API returns.
{"coord":{"lon":144.96,"lat":-37.81},"weather":[{"id":520,"main":"Rain","description":"light
intensity shower
rain","icon":"09n"}],"base":"stations","main":{"temp":288.82,"pressure":1019,"humidity":100,"temp_min":288.15,"temp_max":289.15},"visibility":10000,"wind":{"speed":4.1,"deg":200},"clouds":{"all":90},"dt":1544284800,"sys":{"type":1,"id":9548,"message":0.5221,"country":"AU","sunrise":1544208677,"sunset":1544261597},"id":2158177,"name":"Melbourne","cod":200}
I created a few Struct(s) to get the Json data.
struct CurrentLocalWeather: Decodable {
let base: String
let clouds: Clouds
let cod: Int
let coord: Coord
let dt: Int
let id: Int
let main: Main
let name: String
let sys: Sys
let visibility: Int
let weather: [Weather]
let wind: Wind
}
struct Clouds: Decodable {
let all: Int
}
struct Coord: Decodable {
let lat: Double
let lon: Double
}
struct Main: Decodable {
let humidity: Int
let pressure: Int
let temp: Double
let tempMax: Int
let tempMin: Int
private enum CodingKeys: String, CodingKey {
case humidity, pressure, temp, tempMax = "temp_max", tempMin = "temp_min"
}
}
struct Sys: Decodable {
let country: String
let id: Int
let message: Double
let sunrise: UInt64
let sunset: UInt64
let type: Int
}
struct Weather: Decodable {
let description: String
let icon: String
let id: Int
let main: String
}
struct Wind: Decodable {
let deg: Int
let speed: Double
}
To use those datas this is the code I wrote:
let url = "https://api.openweathermap.org/data/2.5/weather?q=melbourne&APPID=XXXXXXXXXXXXXXXX"
let objurl = URL(string: url)
URLSession.shared.dataTask(with: objurl!) {(data, response, error) in
do {
let forecast = try JSONDecoder().decode([CurrentLocalWeather].self, from: data!)
for weather in forecast {
print(weather.name)
}
} catch {
print("Error")
}
}.resume()
That should print the city name in the console.
Unfortunately it prints Error.
You need
let forecast = try JSONDecoder().decode(CurrentLocalWeather.self, from: data!)
print(forcast.name)
as the root is a dictionary not array

debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil)

I want to load an online json file into my application, but I am running into this error:
typeMismatch(Swift.Array,
Swift.DecodingError.Context(codingPath: [], debugDescription:
"Expected to decode Array but found a dictionary instead.",
underlyingError: nil))
I have looked on stackoverflow but other sollutions didn't help to solve mine.
My JSON:
{
"copyright" : "NHL and the NHL Shield are registered trademarks of the National Hockey League. NHL and NHL team marks are the property of the NHL and its teams. © NHL 2022. All Rights Reserved.",
"totalItems" : 0,
"totalEvents" : 0,
"totalGames" : 0,
"totalMatches" : 0,
"metaData" : {
"timeStamp" : "20220813_172145"
},
"wait" : 10,
"dates" : [ ]
}
My datamodel:
import Foundation
struct Initial: Codable {
let copyright: String
let totalItems: Int
let totalEvents: Int
let totalGames: Int
let totalMatches: Int
let wait: Int
let dates: [Dates]
}
struct Dates: Codable {
let date: String
let totalItems: Int
let totalEvents: Int
let totalGames: Int
let totalMatches: Int
let games: [Game]
}
struct Game: Codable {
let gamePk: Int
let link: String
let gameType: String
let season: String
let gameDate: String
let status: Status
let teams: Team
let venue: Venue
let content: Content
}
struct Status: Codable {
let abstractGameState: String
let codedGameState: Int
let detailedState: String
let statusCode: Int
let startTimeTBD: Bool
}
struct Team: Codable {
let away: Away
let home: Home
}
struct Away: Codable {
let leagueRecord: LeagueRecord
let score: Int
let team: TeamInfo
}
struct Home: Codable {
let leagueRecord: LeagueRecord
let score: Int
let team: TeamInfo
}
struct LeagueRecord: Codable {
let wins: Int
let losses: Int
let type: String
}
struct TeamInfo: Codable {
let id: Int
let name: String
let link: String
}
struct Venue: Codable {
let name: String
let link: String
}
struct Content: Codable {
let link: String
}
and here is my viewcontroller
import UIKit
class TodaysGamesTableViewController: UITableViewController {
var todaysGamesURL: URL = URL(string: "https://statsapi.web.nhl.com/api/v1/schedule")!
var gameData: [Dates] = []
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
override func viewDidLoad() {
super.viewDidLoad()
loadTodaysGames()
}
func loadTodaysGames(){
print("load Games")
view.addSubview(activityIndicator)
activityIndicator.frame = view.bounds
activityIndicator.startAnimating()
let todaysGamesDatatask = URLSession.shared.dataTask(with: todaysGamesURL, completionHandler: dataLoaded)
todaysGamesDatatask.resume()
}
func dataLoaded(data:Data?,response:URLResponse?,error:Error?){
if let detailData = data{
print("detaildata", detailData)
let decoder = JSONDecoder()
do {
let jsondata = try decoder.decode([Dates].self, from: detailData)
gameData = jsondata //Hier .instantie wil doen krijg ik ook een error
DispatchQueue.main.async{
self.tableView.reloadData()
}
}catch let error{
print(error)
}
}else{
print(error!)
}
}
Please learn to understand the decoding error messages, they are very descriptive.
The error says you are going to decode an array but the actual object is a dictionary (the target struct).
First take a look at the beginning of the JSON
{
"copyright" : "NHL and the NHL Shield are registered trademarks of the National Hockey League. NHL and NHL team marks are the property of the NHL and its teams. © NHL 2018. All Rights Reserved.",
"totalItems" : 2,
"totalEvents" : 0,
"totalGames" : 2,
"totalMatches" : 0,
"wait" : 10,
"dates" : [ {
"date" : "2018-05-04",
It starts with a { which is a dictionary (an array is [) but you want to decode an array ([Dates]), that's the type mismatch the error message is referring to.
But this is only half the solution. After changing the line to try decoder.decode(Dates.self you will get another error that there is no value for key copyright.
Look again at the JSON and compare the keys with the struct members. The struct whose members match the JSON keys is Initial and you have to get the dates array to populate gameData.
let jsondata = try decoder.decode(Initial.self, from: detailData)
gameData = jsondata.dates
The JSON is represented by your Initial struct, not an array of Dates.
Change:
let jsondata = try decoder.decode([Dates].self, from: detailData)
to:
let jsondata = try decoder.decode(Initial.self, from: detailData)
Correct Answer is done previously from my two friends
but you have to do it better i will provide solution for you to make code more clean and will give you array of Dates
here is your model with codable
import Foundation
struct Initial: Codable {
let copyright: String
let totalItems: Int
let totalEvents: Int
let totalGames: Int
let totalMatches: Int
let wait: Int
let dates: [Dates]
}
struct Dates: Codable {
let date: String
let totalItems: Int
let totalEvents: Int
let totalGames: Int
let totalMatches: Int
let games: [Game]
}
struct Game: Codable {
let gamePk: Int
let link: String
let gameType: String
let season: String
let gameDate: String
let status: Status
let teams: Team
let venue: Venue
let content: Content
}
struct Status: Codable {
let abstractGameState: String
let codedGameState: Int
let detailedState: String
let statusCode: Int
let startTimeTBD: Bool
}
struct Team: Codable {
let away: Away
let home: Home
}
struct Away: Codable {
let leagueRecord: LeagueRecord
let score: Int
let team: TeamInfo
}
struct Home: Codable {
let leagueRecord: LeagueRecord
let score: Int
let team: TeamInfo
}
struct LeagueRecord: Codable {
let wins: Int
let losses: Int
let type: String
}
struct TeamInfo: Codable {
let id: Int
let name: String
let link: String
}
struct Venue: Codable {
let name: String
let link: String
}
struct Content: Codable {
let link: String
}
// MARK: Convenience initializers
extension Initial {
init(data: Data) throws {
self = try JSONDecoder().decode(Initial.self, from: data)
}
}
And Here is Controller Will make solution more easy
class ViewController: UIViewController {
var todaysGamesURL: URL = URL(string: "https://statsapi.web.nhl.com/api/v1/schedule")!
var gameData: Initial?
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
override func viewDidLoad() {
super.viewDidLoad()
self.loadTodaysGames()
}
func loadTodaysGames(){
print("load Games")
let todaysGamesDatatask = URLSession.shared.dataTask(with: todaysGamesURL, completionHandler: dataLoaded)
todaysGamesDatatask.resume()
}
func dataLoaded(data:Data?,response:URLResponse?,error:Error?){
if let detailData = data {
if let inital = try? Initial.init(data: detailData){
print(inital.dates)
}else{
// print("Initial")
}
}else{
print(error!)
}
}
}

JSON decodable swift 4

I'm having a terrible time creating a public struct for the following JSON. I'm trying to extract the temp and humidity. I've tried to to extract the following JSON but I think I'm having a problem with way I'm identifying each of the variables.
Here's the JSON:
{"coord":{"lon":-82.26,"lat":27.76},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"base":"stations","main":{"temp":66.24,"pressure":1021,"humidity":63,"temp_min":62.6,"temp_max":69.8},"visibility":16093,"wind":{"speed":8.05,"deg":80},"clouds":{"all":90},"dt":1523500500,"sys":{"type":1,"id":726,"message":0.0051,"country":"US","sunrise":1523531237,"sunset":1523577156},"id":420006939,"name":"Brandon","cod":200}
And here's the struct
public struct Page: Decodable {
private enum CodingKeys : String, CodingKey {
case coord = "coord", weather = "weather", mainz = "main", visibility = "visibility", wind = "wind", clouds = "clouds", dt = "dt", sys = "sys", id = "id", name = "name", cod = "cod"}
let coord: String
let weather: [String]
let mainz: String
let visibility: Int
let wind: String
let clouds: String
let dt: Int
let sys: String
let id: Int
let name: String
let cod: Int
public struct Main: Decodable {
private enum CodingKeys : String, CodingKey {
case temp = "temp", pressure = "pressure",humidity = "humidity", temp_min = "temp_min", temp_max = "temp_max"
}
let temp: Int
let pressure: Int
let humidity: Int
let temp_min: Int
let temp_max: Int
}
...and the code I'm using the decode...
// Make the POST call and handle it in a completion handler
let task = session.dataTask(with: components.url!, completionHandler: {(data, response, error) in
guard let data = data else { return }
do
{
let result = try JSONDecoder().decode(Page.self, from: data)
for main in result.mainz {
print(main.humidity)
}
}catch
{print("Figure it out")
}
})
task.resume()
Create structures to capture whatever you want. For example, if you're interested in the temperatures and the coordinates, create structures for those:
struct WeatherTemperature: Codable {
let temp: Double
let pressure: Double
let humidity: Double
let tempMin: Double
let tempMax: Double
}
struct WeatherCoordinate: Codable {
let latitude: Double
let longitude: Double
enum CodingKeys: String, CodingKey {
case latitude = "lat"
case longitude = "lon"
}
}
Then create a structure for the whole response:
struct ResponseObject: Codable {
let coord: WeatherCoordinate
let main: WeatherTemperature
}
Note, I only create properties for those keys I care about.
And then decode it:
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let responseObject = try decoder.decode(ResponseObject.self, from: data)
print(responseObject.coord)
print(responseObject.main)
} catch {
print(error)
}
That resulted in:
WeatherCoordinate #1(latitude: 27.760000000000002, longitude: -82.260000000000005)
WeatherTemperature #1(temp: 66.239999999999995, pressure: 1021.0, humidity: 63.0, tempMin: 62.600000000000001, tempMax: 69.799999999999997)
Clearly, add whatever other structures/properties you care about, but hopefully this illustrates the idea.
Note, I'd rather not let the JSON dictate my property names, so, for example, I specified a key decoding strategy for my decoder to convert from JSON snake_case to Swift camelCase.
I also like longer property names, so where I wanted more expressive names (latitude and longitude rather than lat and lon), I defined CodingKeys for those. But do whatever you want on this score.

structure for Decodable JSON

I am trying to put the following API link into a Decodable JSON in Swift
Link Here
Below is the code to map the link:
import Foundation
struct SelectedCompany: Decodable {
let LastTradePrice: Double
let ListedCompanyID: String
let ListedCompanyName: String
let MarketTotalOrdersByOrder: Int
let MarketTotalOrdersByPrice: Int
let MarketTotalSharesByOrder: Int
let MarketTotalSharesByPrice: Int
let NumberOfTrades: Int
let Value: Int
let Volume: Int
let MarketAskOrdersByOrder: [Order]
let MarketAskOrdersByPrice: [Order]
let MarketBidOrdersByOrder: [Order]
let MarketBidOrdersByPrice: [Order]
let VWAP: Int
}
struct Order: Decodable {
let Price: Double
let Shares: Int
}
Any idea why is not mapping correctly? When I try to run it in the simulator, I am getting the below error
dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})))
Thanks
Post Edit:
The error comes when I run the below function in a separate class called Service:
class Service {
static func getSpecificCompany(companyID: String, table: UITableView, completion: #escaping (SelectedCompany) -> ()) {
let link = "https://www.adx.ae/en/_vti_bin/ADX/svc/trading.svc/ListedCompanyOrderBook?listedCompanyID=\(companyID)"
guard let url = URL(string: link) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let resultData = data else { return }
do {
let resultCompany = try JSONDecoder().decode(SelectedCompany.self, from: resultData)
DispatchQueue.main.async {
completion(resultCompany)
table.reloadData()
}
} catch {
print(error)
}
}.resume()
}
}
In the ViewController class, the above function will be as follows:
class SomeViewController: UIViewController {
#IBOutlet weak var myTable: UITableView!
var selectedCompany:[SelectedCompany]?
var companyID = String()
override func viewDidLoad() {
super.viewDidLoad()
Service.getSpecificCompany(companyID: companyID, table: myTable) { (company) in
self.selectedCompany = company
}
}
}
The only problem with your structs is the presence of this sort of thing in the JSON:
{"Price":null,"Shares":null}
To cope with that, you need to rewrite your Order struct to allow for null:
struct Order: Decodable {
let Price: Double?
let Shares: Int?
}
As soon as I do that, I can successfully decode the JSON you showed using your SelectedCompany and Order.
Here is playground code that tests (successfully):
let json = """
{"LastTradePrice":3.87,"ListedCompanyID":"ADIB","ListedCompanyName":"Abu Dhabi Islamic Bank","MarketAskOrdersByOrder":[{
"Price":3.87,"Shares":100000},{
"Price":3.88,"Shares":100000},{
"Price":3.88,"Shares":6000},{
"Price":3.89,"Shares":100000},{
"Price":3.9,"Shares":30000},{
"Price":3.9,"Shares":100000},{
"Price":3.98,"Shares":99800},{
"Price":3.98,"Shares":10000},{
"Price":3.99,"Shares":75000},{
"Price":3.99,"Shares":285018},{
"Price":4,"Shares":100000},{
"Price":4,"Shares":100000},{
"Price":4,"Shares":10000},{
"Price":4,"Shares":6336},{
"Price":4,"Shares":100000},{
"Price":4.09,"Shares":5000},{
"Price":4.1,"Shares":50000},{
"Price":4.11,"Shares":5000},{
"Price":4.13,"Shares":28894},{
"Price":4.13,"Shares":25000}],"MarketAskOrdersByPrice":[{
"Price":3.87,"Shares":100000},{
"Price":3.88,"Shares":106000},{
"Price":3.89,"Shares":100000},{
"Price":3.9,"Shares":130000},{
"Price":3.98,"Shares":109800},{
"Price":3.99,"Shares":360018},{
"Price":4,"Shares":316336},{
"Price":4.09,"Shares":5000},{
"Price":4.1,"Shares":50000},{
"Price":4.11,"Shares":5000},{
"Price":4.13,"Shares":53894},{
"Price":4.14,"Shares":193000},{
"Price":4.15,"Shares":85000},{
"Price":4.2,"Shares":127211},{
"Price":4.25,"Shares":250000},{
"Price":4.26,"Shares":10000}],"MarketBidOrdersByOrder":[{
"Price":3.85,"Shares":5349},{
"Price":3.85,"Shares":200000},{
"Price":3.84,"Shares":70000},{
"Price":3.84,"Shares":300000},{
"Price":3.83,"Shares":75000},{
"Price":3.81,"Shares":28000},{
"Price":3.8,"Shares":700000},{
"Price":3.79,"Shares":100000},{
"Price":3.79,"Shares":10000},{
"Price":3.72,"Shares":50000},{
"Price":3.68,"Shares":100000},{
"Price":3.67,"Shares":15000},{
"Price":3.67,"Shares":25000},{
"Price":null,"Shares":null},{
"Price":null,"Shares":null},{
"Price":null,"Shares":null},{
"Price":null,"Shares":null},{
"Price":null,"Shares":null},{
"Price":null,"Shares":null},{
"Price":null,"Shares":null}],"MarketBidOrdersByPrice":[{
"Price":3.85,"Shares":205349},{
"Price":3.84,"Shares":370000},{
"Price":3.83,"Shares":75000},{
"Price":3.81,"Shares":28000},{
"Price":3.8,"Shares":700000},{
"Price":3.79,"Shares":110000},{
"Price":3.72,"Shares":50000},{
"Price":3.68,"Shares":100000},{
"Price":3.67,"Shares":40000},{
"Price":null,"Shares":null},{
"Price":null,"Shares":null},{
"Price":null,"Shares":null},{
"Price":null,"Shares":null},{
"Price":null,"Shares":null},{
"Price":null,"Shares":null},{
"Price":null,"Shares":null}],"MarketTotalOrdersByOrder":28,"MarketTotalOrdersByPrice":16,"MarketTotalSharesByOrder":1678349,"MarketTotalSharesByPrice":1678349,"NumberOfTrades":41,"VWAP":0,"Value":7159043,"Volume":1863558}
"""
let jsondata = json.data(using: .utf8)
struct SelectedCompany: Decodable {
let LastTradePrice: Double
let ListedCompanyID: String
let ListedCompanyName: String
let MarketTotalOrdersByOrder: Int
let MarketTotalOrdersByPrice: Int
let MarketTotalSharesByOrder: Int
let MarketTotalSharesByPrice: Int
let NumberOfTrades: Int
let Value: Int
let Volume: Int
let MarketAskOrdersByOrder: [Order]
let MarketAskOrdersByPrice: [Order]
let MarketBidOrdersByOrder: [Order]
let MarketBidOrdersByPrice: [Order]
let VWAP: Int
}
struct Order: Decodable {
let Price: Double?
let Shares: Int?
}
do {
let result = try JSONDecoder().decode(SelectedCompany.self, from: jsondata!)
print(result) // works fine
} catch {
print(error) // no error
}