快速解码JSON数组

时间:2019-04-07 11:01:35

标签: json swift decoding

我正在尝试从JSON中对Swift中的对象数组进行解码,但是即使尝试了多次小调整也无法正常工作。

我有一个名为ReviewData的Decodable结构,它具有多个字段(我仅显示两个字段以使其更具可读性),目前我是从php网站获取它的,它只是输出原始值(您可以看到输出{ {3}})。 我尝试通过在开头/结尾处添加{}以及添加一个名为ReviewDataList的Decodable结构来稍微调整输出值,该结构只包含一个ReviewData数组。

这是我当前拥有的代码:

struct ReviewDataList : Decodable, Encodable {
    let values: [ReviewData]
    enum CodingKeys : String, CodingKey {
        case values = "" // Since the received JSON has no "name", I didn't specify anything here
    }
}

struct ReviewData : Decodable, Encodable {
    let id: Int
    let name: String

    enum CodingKeys : String, CodingKey {
        case id = "id"
        case name = "name"
    }
}

func fetchReviews(){
        [...]
        URLSession.shared.dataTask(with: request) { data, response, error in
            if data != nil {
                guard let decoded = try? JSONDecoder().decode([ReviewData].self, from: data!) else {
                    print("Couldn't decode data to get reviews. Data: \(String(data: modifiedData, encoding: .utf8)!)")
                    return
                }
            }
        [...]
}

// I also tried adding "{\"\":" at the beginning and "}" at the end of the data to make it conform to the ReviewDataList format.

如果有效,它应该输出ReviewData的数组(隐藏在ReviewDataList中或直接作为[ReviewData]的数组),但是解码方法根本不起作用,并且总是输出“无法解码数据以获取评论”。 任何帮助都将受到欢迎!谢谢!

2 个答案:

答案 0 :(得分:0)

您从服务器获取的JSON出现问题。 \"\n键值中有summaryopinion。我尝试将其删除,并且您的工作JSON如下所示:

let jsonData = """
        [
    {
        "id": "20",
        "name": "A.I.C.O. Incarnation",
        "mark": "3",
        "cat1": "0",
        "cat2": "5",
        "cat3": "-1",
        "summary": "In 2035, a biological research project to create an Artificial and Intelligent Cellular Organism (A.I.C.O.) went awry, resulting in an incident called the Burst which transformed Kurobe Gorge into a quarantine area infested by a rampant growth of synthetic organisms called Matter. Two years later, high school student Aiko Tachibana finds that she may be the duplicate of a girl trapped within the Matter whose family disappeared in the Burst. An enigmatic fellow student Yuya Kanzaki offers to solve the mystery by taking her with a group of professional Divers to the Primary Point which was the center of the Burst.",
        "opinion": "Pretty ok anime! Nothing out of this world either, but the story is nice.Yuya is extremely boring though.Overall, the story is nice, some characters are interesting and the action scenes against the Matter are cool!",
        "creation": "2019-04-05"
    },
    {
        "id": "21",
        "name": "Anohana: The Flower We Saw That Day",
        "mark": "4",
        "cat1": "6",
        "cat2": "4",
        "cat3": "7",
        "summary": "A group of six sixth-grade-age childhood friends drift apart after one of them, Meiko Menma Honma, dies in an accident. Years after the incident, the leader of the group, Jinta Yadomi, has withdrawn from society, does not attend high school, and lives as a recluse. One summer day, the ghost of an older-looking Menma appears beside him and asks to have a wish granted, reasoning that she cannot pass on into the afterlife until it is fulfilled. At first, he only tries to help her minimally because he thinks he is hallucinating. But since Menma does not remember what her wish is, Jinta gathers his estranged friends together once again, believing that they are the key to resolving this problem. All of the group joins him, though most of them do so reluctantly. However, things grow increasingly complicated when his friends accuse him of not being able to get over the death of Menma, for Jinta is the only one who can see Menma's ghost and his friends think he is seeing things. But as matters progress, it is realized that Jinta is not the only person in the group who is having trouble letting go of the past and later then Menma shows her presence to the group to prove that she is indeed real. It is revealed that all of the group members blame themselves for Menma's death and long-hidden feelings are rekindled. The group struggles as they grow from trying to help Menma move on and help each other move on as well.",
        "opinion": "It’s really nice!!The story is really intense event if the basic plot may seem a bit basic. It only gets interesting after episode 3/4, but it’s worth it!The ending (the last two episode basically) are really emotional, which makes it even better!",
        "creation": "2019-04-05"
    },
    {
        "id": "22",
        "name": "Assassination Classroom",
        "mark": "3",
        "cat1": "6",
        "cat2": "0",
        "cat3": "-1",
        "summary": "Earth is threatened by the sudden appearance of an enormously powerful monster who apparently destroyed 70% of the Moon, leaving it permanently shaped like a crescent. The monster claims that within a year he will destroy the planet next, but he offers mankind a chance to avert this fate. In class 3-E, the End Class of Kunugigaoka Junior High School, he starts working as a homeroom teacher where he teaches his students regular subjects, as well as the ways of assassination. The Japanese government promises a reward of ¥10 billion (i.e. 100 million USD) to whoever among the students succeeds in killing the creature, whom they have named Koro-sensei. However, this proves to be a nigh-impossible task, as not only does he have several superpowers at his disposal, including accelerated regeneration and the ability to move and fly at Mach 20, but he is also the best teacher they could ask for, helping them to improve their grades, individual skills, and prospects for the future.As the series goes on, the situation gets even more complicated as other assassins come after Koro-sensei's life, some coveting the reward, others for personal reasons. The students eventually learn the secrets involving him, the Moon's destruction and his ties with their previous homeroom teacher, including the true reason why he must be killed before the end of the school year. The series is narrated by Nagisa Shiota, one of the pupils in the class whose main strategy in killing Koro-sensei is making a list of all his weaknesses. At first, Nagisa appears to be one of the weaker members of Class 3-E, but he later emerges as one of the most skillful assassins in the class.",
        "opinion": "I don’t know how this anime is so hyped. It’s okay, but most of it is just boring, with little to no action sometimes and characters that are introduced to disappear quickly.The characters are however really charismatic, and it really is fun to follow their daily life!Good but overrated overall.",
        "creation": "2019-04-05"
    }
]
""".data(using: .utf8)!

,您可以在Codable下面进行解析:

typealias ReviewDataList = [ReviewDataListElement]

struct ReviewDataListElement: Codable {
    let id, name, mark, cat1: String
    let cat2, cat3, summary, opinion: String
    let creation: String
}

do {
        let reviewDataList = try JSONDecoder().decode(ReviewDataList.self, from: jsonData)
        print(reviewDataList)
    } catch {
        print(error)
    }

在操场上检查并给出以下结果:

[test.ReviewDataListElement(id: "20", name: "A.I.C.O. Incarnation", mark: "3", cat1: "0", cat2: "5", cat3: "-1", summary: "In 2035, a biological research project to create an Artificial and Intelligent Cellular Organism (A.I.C.O.) went awry, resulting in an incident called the Burst which transformed Kurobe Gorge into a quarantine area infested by a rampant growth of synthetic organisms called Matter. Two years later, high school student Aiko Tachibana finds that she may be the duplicate of a girl trapped within the Matter whose family disappeared in the Burst. An enigmatic fellow student Yuya Kanzaki offers to solve the mystery by taking her with a group of professional Divers to the Primary Point which was the center of the Burst.", opinion: "Pretty ok anime! Nothing out of this world either, but the story is nice.Yuya is extremely boring though.Overall, the story is nice, some characters are interesting and the action scenes against the Matter are cool!", creation: "2019-04-05"), test.ReviewDataListElement(id: "21", name: "Anohana: The Flower We Saw That Day", mark: "4", cat1: "6", cat2: "4", cat3: "7", summary: "A group of six sixth-grade-age childhood friends drift apart after one of them, Meiko Menma Honma, dies in an accident. Years after the incident, the leader of the group, Jinta Yadomi, has withdrawn from society, does not attend high school, and lives as a recluse. One summer day, the ghost of an older-looking Menma appears beside him and asks to have a wish granted, reasoning that she cannot pass on into the afterlife until it is fulfilled. At first, he only tries to help her minimally because he thinks he is hallucinating. But since Menma does not remember what her wish is, Jinta gathers his estranged friends together once again, believing that they are the key to resolving this problem. All of the group joins him, though most of them do so reluctantly. However, things grow increasingly complicated when his friends accuse him of not being able to get over the death of Menma, for Jinta is the only one who can see Menma\'s ghost and his friends think he is seeing things. But as matters progress, it is realized that Jinta is not the only person in the group who is having trouble letting go of the past and later then Menma shows her presence to the group to prove that she is indeed real. It is revealed that all of the group members blame themselves for Menma\'s death and long-hidden feelings are rekindled. The group struggles as they grow from trying to help Menma move on and help each other move on as well.", opinion: "It’s really nice!!The story is really intense event if the basic plot may seem a bit basic. It only gets interesting after episode 3/4, but it’s worth it!The ending (the last two episode basically) are really emotional, which makes it even better!", creation: "2019-04-05"), test.ReviewDataListElement(id: "22", name: "Assassination Classroom", mark: "3", cat1: "6", cat2: "0", cat3: "-1", summary: "Earth is threatened by the sudden appearance of an enormously powerful monster who apparently destroyed 70% of the Moon, leaving it permanently shaped like a crescent. The monster claims that within a year he will destroy the planet next, but he offers mankind a chance to avert this fate. In class 3-E, the End Class of Kunugigaoka Junior High School, he starts working as a homeroom teacher where he teaches his students regular subjects, as well as the ways of assassination. The Japanese government promises a reward of ¥10 billion (i.e. 100 million USD) to whoever among the students succeeds in killing the creature, whom they have named Koro-sensei. However, this proves to be a nigh-impossible task, as not only does he have several superpowers at his disposal, including accelerated regeneration and the ability to move and fly at Mach 20, but he is also the best teacher they could ask for, helping them to improve their grades, individual skills, and prospects for the future.As the series goes on, the situation gets even more complicated as other assassins come after Koro-sensei\'s life, some coveting the reward, others for personal reasons. The students eventually learn the secrets involving him, the Moon\'s destruction and his ties with their previous homeroom teacher, including the true reason why he must be killed before the end of the school year. The series is narrated by Nagisa Shiota, one of the pupils in the class whose main strategy in killing Koro-sensei is making a list of all his weaknesses. At first, Nagisa appears to be one of the weaker members of Class 3-E, but he later emerges as one of the most skillful assassins in the class.", opinion: "I don’t know how this anime is so hyped. It’s okay, but most of it is just boring, with little to no action sometimes and characters that are introduced to disappear quickly.The characters are however really charismatic, and it really is fun to follow their daily life!Good but overrated overall.", creation: "2019-04-05")]

答案 1 :(得分:0)

我遇到的问题是,我收到的JSON通过在它们周围添加“”来将所有Int / Float类型解析为字符串,因此我的JSON解析找不到所需的Int / Float!