skip to Main Content

I’m trying to parse Json to a struct but I keep getting the error message:

The data couldn’t be read because it isn’t in the correct format.

Pretty much what I’m trying to do is print the ‘extract’ part to the console.

The struct is the following:

struct WikiContent: Codable {
    let batchcomplete: Bool
    let query: QueryStruct }

struct QueryStruct: Codable{
    let pages: [PageStruct] }

struct PageStruct: Codable {
    let pageid: Int!
    let ns: Int!
    let title: String!
    let extract: String! }

The Json:

{
    batchcomplete: true,
    query: {
        pages: [
        {
            pageid: 7134310,
            ns: 0,
            title: "Matt Hancock",
            extract: "Matthew John David Hancock (born 2 October 1978) is a British politician serving as Secretary of State for Health and Social Care since 2018. He previously served as Secretary of State for Digital, Culture, Media and Sport in 2018, for six months. A member of the Conservative Party, he has been Member of Parliament (MP) for West Suffolk since 2010. Hancock was born in Cheshire, where his family runs a software business. Hancock studied for a BA in Philosophy, Politics and Economics (PPE) at Exeter College, Oxford, and an MPhil in Economics at Christ's College, Cambridge, as a postgraduate student. He was an economist at the Bank of England before serving as a senior economic adviser and then later Chief of Staff to Shadow Chancellor of the Exchequer George Osborne. Hancock served as a Junior Minister at the Department for Business, Innovation and Skills from September 2013 to May 2015. He attended David Cameron's Cabinet as Minister for the Cabinet Office from 2015 to 2016. After Theresa May became Prime Minister in 2016, Hancock was demoted to Minister of State for Digital and Culture. He was promoted to May's Cabinet in the January 2018 cabinet reshuffle when he was appointed Secretary of State for Digital, Culture, Media and Sport.On 9 July 2018, after the promotion of Jeremy Hunt to Foreign Secretary, Hancock was named as his replacement, and was elevated to the position of Secretary of State for Health and Social Care. On 25 May 2019, he announced his intention to stand in the 2019 Conservative Party leadership election. He withdrew from the race on 14 June, shortly after the first ballot. After endorsing Boris Johnson, he was retained in his Cabinet in July 2019. He served as Health Secretary during the COVID-19 pandemic in the United Kingdom and subsequent rollout of the UK's vaccination programme. "
            },
            {
            pageid: 19065069,
            ns: 0,
            title: "Boris Johnson",
            extract: "Alexander Boris de Pfeffel Johnson (; born 19 June 1964) is a British politician and writer serving as Prime Minister of the United Kingdom and Leader of the Conservative Party since July 2019. He was Secretary of State for Foreign and Commonwealth Affairs from 2016 to 2018 and Mayor of London from 2008 to 2016. Johnson has been Member of Parliament (MP) for Uxbridge and South Ruislip since 2015 and was previously MP for Henley from 2001 to 2008. He has been described as adhering to the ideology of one-nation and national conservatism.Johnson was educated at Eton College and studied Classics at Balliol College, Oxford. He was elected President of the Oxford Union in 1986. In 1989, he became the Brussels correspondent, and later political columnist, for The Daily Telegraph, where his articles exerted a strong Eurosceptic influence on the British right. He was editor of The Spectator magazine from 1999 to 2005. After being elected to Parliament in 2001, Johnson was a shadow minister under Conservative leaders Michael Howard and David Cameron. In 2008, he was elected Mayor of London and resigned from the House of Commons; he was re-elected as mayor in 2012. During his mayoralty, Johnson oversaw the 2012 Summer Olympics and the cycle hire scheme, both initiated by his predecessor, along with introducing the New Routemaster buses, the Night Tube, and the Thames cable car and promoting the Garden Bridge. He also banned alcohol consumption on much of London's public transport. In the 2015 election, Johnson was elected MP for Uxbridge and South Ruislip. The following year, he did not seek re-election as mayor; he became a prominent figure in the successful Vote Leave campaign for Brexit in the 2016 EU membership referendum. He was appointed foreign secretary by Theresa May after the referendum; he resigned the position two years later in protest at May's approach to Brexit and the Chequers Agreement. After May resigned in 2019, he was elected Conservative leader and appointed prime minister. His September 2019 prorogation of Parliament was ruled unlawful by the Supreme Court. In the 2019 election, Johnson led the Conservative Party to its biggest parliamentary victory since 1987, winning 43.6% of the vote – the largest share of any party since 1979. The United Kingdom withdrew from the EU under the terms of a revised Brexit withdrawal agreement, entering into a transition period and trade negotiations leading to the EU–UK Trade and Cooperation Agreement. Johnson has led the United Kingdom's ongoing response to the COVID-19 pandemic.Johnson is considered a controversial figure in UK politics. Supporters have praised him as humorous and entertaining, with an appeal stretching beyond traditional Conservative voters. Conversely, his critics have accused him of elitism, cronyism, and bigotry. His actions that are viewed by some as pragmatic tend to be viewed by opponents as opportunistic."
            }
        ]
    }
}

The code:

func fetchData(){
        let url = URL(string: "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles=Matt%20Hancock%7CBoris%20Johnson&formatversion=2&exintro=1&explaintext=1")!
        
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data else {return}
            print(data)
            
            do{
                let wikiData = try JSONDecoder().decode([WikiContent].self, from: data)
            }
            catch{
                
            let error = error
                print(error.localizedDescription)
            }
        }.resume()
    }

2

Answers


  1. You’re trying to decode an array of WikiContent, but it isn’t an array — it’s just a single object:

    do{
        let wikiData = try JSONDecoder().decode(WikiContent.self, from: data)
        print(wikiData)
    }
    catch {
        print(error)
    }
    

    Tip: printing error gives much more useful information than error.localizedDescription

    Login or Signup to reply.
  2.  do{
         let wikiData = try JSONDecoder().decode(WikiContent.self, from: data)
      }catch{
             print(error.localizedDescription)
      }
    

    Data is getting initially dictionary format, but not its an array so remove array of WikiContent

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search