在swift中解码JSON数组

问题描述 投票:-1回答:2

我试图从JSON中解码Swift中的一个对象数组,但即使尝试多次小调整它也不起作用。

我有一个名为ReviewData的Decodable结构,它有多个字段(我只显示两个以使其更具可读性),我目前从php网站上获取它,它只是输出原始值(你可以看到输出here)。我尝试通过在开头/结尾添加{}来稍微调整输出值,以及添加一个名为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]),但解码方法根本不起作用,它总是输出“无法解码数据来获得评论”。欢迎任何帮助!谢谢!

json swift decoding
2个回答
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")]

0
投票

我遇到的问题是我收到的JSON通过添加“围绕它们来解析所有Int / Float类型作为字符串,所以我的JSON解析无法找到它想要的Int / Float!

© www.soinside.com 2019 - 2024. All rights reserved.