PR10
PR10

Reputation: 3

How to display parsed JSON data in Swift?

After parsing JSON trough an API call i've had trouble converting the parsed JSON into the data that i want to display in my ViewController. I am able to print the JSON data in the console but i am not able to only get the value of "word: .." from the data i want to display. This is an example of a JSON object:

{
  "metadata": {},
  "results": [
    {
      "id": "eurhythmic",
      "word": "eurhythmic"
    }
  ]
}

The struct i'm using is the following:

// Struct RandomWords
struct StoreRandomWords: Codable {
    let results: [Result]
}

struct Result: Codable {
    let word: String
}

The code to fetch the data from the API:

func fetchRandomWord(completion: @escaping (StoreRandomWords?) -> Void) {
        let language = "en"
        let filters = "registers%3DRare%3Bdomains%3DArt?"
        let limit = "limit=1"
        let url = URL(string: "https://od-api.oxforddictionaries.com:443/api/v1/wordlist/\(language)/\(filters)\(limit)")!
        var request = URLRequest(url: url)
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.addValue(appId, forHTTPHeaderField: "app_id")
        request.addValue(appKey, forHTTPHeaderField: "app_key")

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                do {
                let jsonData = try JSONDecoder().decode(StoreRandomWords.self, from: data)
                print(jsonData)
                } catch {
                    print(error)
                }
            } else {
                print(error)
                print(NSString.init(data: data!, encoding: String.Encoding.utf8.rawValue)!)
            }
        }
        task.resume()
    }

And the code from ViewController in which i want to load the "word":

// Do any additional setup after loading the view.
override func viewDidLoad() {
    super.viewDidLoad()

    // Fetch data for Daily Word.
    ContextController.shared.fetchRandomWord( completion: { (storeRandomWord) in
        if let storeRandomWord = storeRandomWord {
          //

        }
    })
  }

Which gives me this output in the console:

StoreRandomWords(results: [GetContext.Result(word: "eurhythmic")])

And my goal is to literally display the value word which is here "eurhythmic".

(I'm a beginner and not a native speaker of English so any feedback on how to improve the code or the question would be helpful and welcome to. )

Upvotes: 0

Views: 827

Answers (1)

Sergio Trejo
Sergio Trejo

Reputation: 633

You will have to loop the array or access the index science storeRandomWords.results is an array.

For example print the first result:

if let storeRandomWord = storeRandomWord {
    print(storeRandomWord.results.first.word)
}

Upvotes: 1

Related Questions