1

enter image description hereenter image description hereHello 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
}
4
  • 1
    Your struct doesn't match the JSON. Make them Codable instead of Decodable only, and do let root = Root(first..., ie create an instance, and use JSONEncoder() to see what's the "compatible" JSON with your struct. You'll see... Commented Jul 18, 2022 at 11:10
  • What is a PostPresenter? What does it represent? Commented Jul 18, 2022 at 11:38
  • The data from API Commented Jul 18, 2022 at 11:46
  • No it's not. The response parameter is from the API. What is PostPresenter supposed to represent? Commented Jul 18, 2022 at 12:51

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

Cannot assign value of type '[Datum]' to type 'String' is the error for the datum. I am trying to solve it. The last one before the successful run
What is the URL that causes that error? The one you provided does not.
I refresh the question. Take a look. thanks.
Your title var is a String, the data is not a String. It's an array of Datum objects.

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.