JSON Декодировать SwiftUI - PullRequest
       123

JSON Декодировать SwiftUI

0 голосов
/ 14 июля 2020

У меня проблема с декодированием файла JSON. Я изучаю SwiftUI и работаю с IMDB API. Я скопировал все сертификаты в файл JSON, который я скопировал в документ, чтобы они были доступны в автономном режиме.

Ниже структуры JSON: я не копировал все, так как он довольно длинный, но вы можете видеть структуру В быстром пользовательском интерфейсе я создал такую ​​структуру:

    struct Certification: Codable {
        let certification: String
        let meaning: String
        let order: Int
    }

Я создал расширение Bundle для декодирования файла с использованием типа generi c, и я успешно получаю URL / данные, но защита decodedData не работает

guard let decodedData = try? decoder.decode(T.self, from: data) else {
            
            fatalError("Failed to decoded the data from \(decodable)")
        }

Я получаю фатальную ошибку

Какой правильный тип объявлять для этого JSON. Как мне объявить в SWIFT?

Я объявил глобальную переменную

static let certificates: [String: [Certification]] = Bundle.main.decode("Certifications.json")

Я думаю, что [String: [Certification]] неправильный тип. Какой правильный тип просматривает файл JSON?

Спасибо за помощь!

[
    "US": [
      {
        "certification": "G",
        "meaning": "All ages admitted. There is no content that would be objectionable to most parents. This is one of only two ratings dating back to 1968 that still exists today.",
        "order": 1
      },
      {
        "certification": "PG-13",
        "meaning": "Some material may be inappropriate for children under 13. Films given this rating may contain sexual content, brief or partial nudity, some strong language and innuendo, humor, mature themes, political themes, terror and/or intense action violence. However, bloodshed is rarely present. This is the minimum rating at which drug content is present.",
        "order": 3
      },
      {
        "certification": "R",
        "meaning": "Under 17 requires accompanying parent or adult guardian 21 or older. The parent/guardian is required to stay with the child under 17 through the entire movie, even if the parent gives the child/teenager permission to see the film alone. These films may contain strong profanity, graphic sexuality, nudity, strong violence, horror, gore, and strong drug use. A movie rated R for profanity often has more severe or frequent language than the PG-13 rating would permit. An R-rated movie may have more blood, gore, drug use, nudity, or graphic sexuality than a PG-13 movie would admit.",
        "order": 4
      },
      {
        "certification": "NC-17",
        "meaning": "These films contain excessive graphic violence, intense or explicit sex, depraved, abhorrent behavior, explicit drug abuse, strong language, explicit nudity, or any other elements which, at present, most parents would consider too strong and therefore off-limits for viewing by their children and teens. NC-17 does not necessarily mean obscene or pornographic in the oft-accepted or legal meaning of those words.",
        "order": 5
      },
      {
        "certification": "NR",
        "meaning": "No rating information.",
        "order": 0
      },
      {
        "certification": "PG",
        "meaning": "Some material may not be suitable for children under 10. These films may contain some mild language, crude/suggestive humor, scary moments and/or violence. No drug content is present. There are a few exceptions to this rule. A few racial insults may also be heard.",
        "order": 2
      }
    ],
    "CA": [
      {
        "certification": "18A",
        "meaning": "Persons under 18 years of age must be accompanied by an adult. In the Maritimes & Manitoba, children under the age of 14 are prohibited from viewing the film.",
        "order": 4
      },
      {
        "certification": "G",
        "meaning": "All ages.",
        "order": 1
      },
      {
        "certification": "PG",
        "meaning": "Parental guidance advised. There is no age restriction but some material may not be suitable for all children.",
        "order": 2
      },
      {
        "certification": "14A",
        "meaning": "Persons under 14 years of age must be accompanied by an adult.",
        "order": 3
      },
      {
        "certification": "A",
        "meaning": "Admittance restricted to people 18 years of age or older. Sole purpose of the film is the portrayal of sexually explicit activity and/or explicit violence.",
        "order": 5
      }
    ],

1 Ответ

0 голосов
/ 14 июля 2020

Ваш JSON был недействительным, поэтому я обновил JSON и добавил сюда часть декодирования. Я тестировал это на детских площадках, и он отлично работает.

let data = Data("""
{
"US": [
  {
    "certification": "G",
    "meaning": "All ages admitted. There is no content that would be objectionable to most parents. This is one of only two ratings dating back to 1968 that still exists today.",
    "order": 1
  },
  {
    "certification": "PG-13",
    "meaning": "Some material may be inappropriate for children under 13. Films given this rating may contain sexual content, brief or partial nudity, some strong language and innuendo, humor, mature themes, political themes, terror and/or intense action violence. However, bloodshed is rarely present. This is the minimum rating at which drug content is present.",
    "order": 3
  },
  {
    "certification": "R",
    "meaning": "Under 17 requires accompanying parent or adult guardian 21 or older. The parent/guardian is required to stay with the child under 17 through the entire movie, even if the parent gives the child/teenager permission to see the film alone. These films may contain strong profanity, graphic sexuality, nudity, strong violence, horror, gore, and strong drug use. A movie rated R for profanity often has more severe or frequent language than the PG-13 rating would permit. An R-rated movie may have more blood, gore, drug use, nudity, or graphic sexuality than a PG-13 movie would admit.",
    "order": 4
  },
  {
    "certification": "NC-17",
    "meaning": "These films contain excessive graphic violence, intense or explicit sex, depraved, abhorrent behavior, explicit drug abuse, strong language, explicit nudity, or any other elements which, at present, most parents would consider too strong and therefore off-limits for viewing by their children and teens. NC-17 does not necessarily mean obscene or pornographic in the oft-accepted or legal meaning of those words.",
    "order": 5
  },
  {
    "certification": "NR",
    "meaning": "No rating information.",
    "order": 0
  },
  {
    "certification": "PG",
    "meaning": "Some material may not be suitable for children under 10. These films may contain some mild language, crude/suggestive humor, scary moments and/or violence. No drug content is present. There are a few exceptions to this rule. A few racial insults may also be heard.",
    "order": 2
  }
]
}
""".utf8)

struct Certification: Codable {
    let certification: String
    let meaning: String
    let order: Int
}

do {
    let decodedData = try JSONDecoder().decode([String: [Certification]].self, from: data)
    print(decodedData)
} catch { print(error) }
...