Trouble parsing JSON data, codable structs

Im making an API call using notions API to access and retrieve data from my Notion page and I'm successfully making the url request and accessing the page, however I seem to be struggling with returning the actual data that I have in that page and parsing the JSON data as right now, my console only outputs the makeup of my notion page rather than the formatted and parsed data. I made a codable struct meant to replicate the structure of a notion page based off their documentation then I'm passing that struct to my JSON parsing function but my data still is not being parsed and returned. heres what I have.

import Foundation


struct Page: Codable, Hashable {              //Codable struct for notion "Page" for defining content aswell as object representation in a codable struct of all the basic components that make up a notion page per notion's documentation
    let created_time: String
    let created_by: String
    let last_edited_time: String
    
    
    let object: String
    let cover: String
    let emoji: String
    let icon: String
    
    struct properties: Codable, Hashable {
        let title: String
        let dueDate: String
        let status: String
    }
  
    struct dueDate: Codable, Hashable {
        let id: String
        let type: String
        let date: String
        
        let start: String
        let end: String?           //optionals added to "end" and "time_zone" as these values are set to null in the documentation
        let time_zone: String?
    }
    
    struct Title: Codable,Hashable {
         let id: String
         let type: String
         let title: [String]
    }
    
    struct annotations: Codable, Hashable {
        let bold: Bool
        let italic: Bool
        let strikethrough: Bool
        let underline: Bool
        let code: Bool
        let color: String
    }
    
    let English: String
    let Korean: String
    let Pronounciation: String
                                     

    let in_trash: Bool
    let public_url: String?
    let annotations: Bool
    
}
    
let url = URL(string: "https://api.notion.com/v1/pages/8efc0ca3d9cc44fbb1f34383b794b817")
let apiKey = "secret_Olc3LXnpDW6gI8o0Eu11lQr2krU4b870ryjFPJGCZs4"
let session = URLSession.shared



func makeRequest() {
    if let url = url {
     
        var request = URLRequest(url: url)
        let header = "Bearer " + apiKey          //authorization header declaration
        request.addValue(header, forHTTPHeaderField: "authorization")            //append apikey
        request.addValue("2022-06-28",forHTTPHeaderField: "Notion-Version")          //specify version per notions requirments
       
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let httpError = error {
                print("could not establish HTTP connection:\(httpError)")
            } else {
                if let httpResponse = response as? HTTPURLResponse {
                    if httpResponse.statusCode == 200 {
                    } else {
                        print("invalid api key:\(httpResponse.statusCode)")
                    }
                }
               
            }
        
            if let unwrapData = data {     //safely unwrapping the data value using if let
                if let makeString = String(data: unwrapData, encoding: .utf8) {
                    print(makeString)
                } else {
                       print("no data is being returned:")
                }
                do {
                    let decoder = JSONDecoder()                                 //JSONDecoder method to decode api data,
                    let codeUnwrappedData = try decoder.decode(Page.self,from: unwrapData)     //Page. specifies its a struct, from: passes the data parmeter that contains the api data to be decoded     //PASS STRUCTURESDATABASE STRUCT
                    print("data:\(codeUnwrappedData)")
                   
                    
                } catch {
                    print("could not parse json data")
                }
                
                
                    if let httpResponse = response as? HTTPURLResponse {
                    if httpResponse.statusCode == 200 {
                        print(String(data: unwrapData, encoding: .utf8)!)
                        
                    } else {
                        print("unsuccessful http response:\(httpResponse)")
                    }
                
                }
            }
        
        }
        task.resume()
    }
    
}
  
    
    

Replies

Do you mean the JSON decoding is throwing an error and landing in this catch block?

} catch {
    print("could not parse json data")
}

If so, you should print out the actual error that is being thrown. What does it say?

  • @Scott Yes, that error handler I added does get triggered which is how I know it's a JSON parsing issue. So I'm trying to figure out why my data is not being parsed and returned and what I am doing wrong.

  • In my case its usually a type problem, getting a float when I coded for an Int. date in a a format I did not expect, getting nil value, etc. Add lots of logging and try with data you know is good.

Add a Comment

The error will usually give you a hint as to why parsing failed. I recommend that you print that and study it carefully.

If you can’t figure it out from there, try to cut down the input JSON to something small that you can post here, and we’ll take a look.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

You could also try posting your JSON (remove any sensitive data first!) into a site like https://app.quicktype.io. It'll give you the Swift code for your struct.