首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Json解析和数据无法读取,因为它的格式不正确

Json解析和数据无法读取,因为它的格式不正确
EN

Stack Overflow用户
提问于 2021-06-17 17:51:49
回答 2查看 78关注 0票数 0

我试图将Json解析为一个结构,但我一直收到错误消息:

无法读取数据,因为它的格式不正确。

我想要做的就是把“提取”部分打印到控制台上。

结构如下:

代码语言:javascript
复制
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! }

Json:

代码语言:javascript
复制
{
    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."
            }
        ]
    }
}

守则:

代码语言:javascript
复制
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()
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-06-17 18:03:29

您正在尝试解码一个WikiContent数组,但它不是一个数组--它只是一个对象:

代码语言:javascript
复制
do{
    let wikiData = try JSONDecoder().decode(WikiContent.self, from: data)
    print(wikiData)
}
catch {
    print(error)
}

提示:打印errorerror.localizedDescription提供更多有用的信息

票数 0
EN

Stack Overflow用户

发布于 2021-06-18 19:22:37

代码语言:javascript
复制
 do{
     let wikiData = try JSONDecoder().decode(WikiContent.self, from: data)
  }catch{
         print(error.localizedDescription)
  }

数据最初是字典格式,但不是数组,所以删除WikiContent数组

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68024311

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档