0

I have a JSON encoded data which I download using GCD. You can see how the JSON is encoded from this link: https://quiz2019.herokuapp.com/api/quizzes?token=8fda199c75cb200b0f85

I want to access every single data from that JSON but I can't achieve it. I have tried doing this:

let arrayData = try? JSONSerialization.jsonObject(with: data, options: [])

but after this I don't know how to access every data on the array. Any idea?

1
  • The root object of the JSON is a dictionary, please note the {}. The array is the value for key quizzes. You are encouraged to use Decodable. Commented Nov 20, 2018 at 10:53

2 Answers 2

1

You can try

struct Root: Codable {
    let quizzes: [Quiz]
    let pageno: Int
    let nextURL: String

    enum CodingKeys: String, CodingKey {
        case quizzes, pageno
        case nextURL = "nextUrl"
    }
}

struct Quiz: Codable {
    let id: Int
    let question: String
    let author: Author?
    let attachment: Attachment
    let favourite: Bool
    let tips: [String]
}

struct Attachment: Codable {
    let filename: String
    let mime: MIME
    let url: String
}

enum MIME: String, Codable {
    case imageJPEG = "image/jpeg"
}

struct Author: Codable {
    let id: Int
    let isAdmin: Bool?
    let username: String
}

let roo = try? JSONDecoder().decode(Root.self,from:jsonData)
print(roo)
Sign up to request clarification or add additional context in comments.

2 Comments

This gives me errors saying "Use of undeclared type 'Codable' / 'CodingKey' "
I was using an old version of Xcode. I just downloaded the newest and I could use it, thanks for your answer!
1

You can also use the above native solution by Sh_khan (as native solutions are always best and fast) or an alternative solution is that you can use Object Mapper.

It is the one of the best json parsing library and very easy. Just write a single line:-

let user = Mapper<User>().map(JSONString: JSONString)

You can use Json Export for converting your json into model.

Hope it helps :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.