0

I used https://app.quicktype.io/ to create the structs to decode some JSON and it decodes it successfully.

However, when I try to access the elements within the main object, I am getting a has no member error as follows:

Value of type 'myClass.BookReturned?' has no member 'title'.

This is what the JSON looks like:

{"book":[{"title":"Dreams of Trespass","author":"Fatimah Mernisse","pic":""}]}

struct BookReturned: Codable {
        let book: [Book]
    }
    
    //  Book
struct Book: Codable {
        let title, author, pic: String
    }

This is what the code looks like with the error occuring on the second line

let mybook = try? JSONDecoder().decode(BookReturned.self, from: data)
let author = mybook.title//GIVES THE ERROR

What is the proper way to get the title? If the JSON is malformed, I have the ability to change the JSON as well.

1 Answer 1

2

Please look at the struct BookReturned. There is indeed no member title.

You have to get the first item of the array book, there is the title

let title = mybook.book.first?.title

If the array contains more items you need a loop.

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

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.