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
}
georgekak
  • 73
  • 11
  • 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... – Larme Jul 18 '22 at 11:10
  • What is a `PostPresenter`? What does it represent? – Daniel T. Jul 18 '22 at 11:38
  • The data from API – georgekak Jul 18 '22 at 11:46
  • No it's not. The `response` parameter is from the API. What is `PostPresenter` supposed to represent? – Daniel T. Jul 18 '22 at 12:51

1 Answers1

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
}
Daniel T.
  • 32,821
  • 6
  • 50
  • 72