【问题标题】:Firebase The data couldn’t be read because it isn’t in the correct formatFirebase 无法读取数据,因为它的格式不正确
【发布时间】:2021-10-05 12:15:32
【问题描述】:

我手动导入了 json(json 文件)。解码 json 时出现此错误。

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

我哪里做错了?我的模型错了吗?我的参考有错吗?

JSON:

{
  "allQuiz": [
    {
      "title":"Ağustos Test 1",
      "test": [
        {
          "id": 1,
          "question":"Şekle göre aşağıdakiler hangisi doğrudur",
          "isQuestionImage": true,
          "isSectionImage": false,
          "imageName":"1.png",
          "sections": {
            "A":"2 numaralı aracın öncelikle geçmesi",
            "B":"1 numaralı aracın hızını arttırarak kavşağa girmesi",
            "C":"2 numaralı aracın 3 numaralı aracın geçmesini beklemesi",
            "D":"3 numaralı aracın 2 numaralı aracı ikaz ederek durdurması"
          },
          "correct": "A"
        }
      ]
    }
  ]
}

型号:

struct QuizContainer: Codable {
    var allQuiz: [Quiz]
}

struct Quiz: Codable {
    var title: String
    var test: [Test]
}

enum TestSectionType: String, Codable, Hashable {
    case A = "A"
    case B = "B"
    case C = "C"
    case D = "D"
}

struct Test: Codable {
    var id: Int
    var question: String
    var isQuestionImage: Bool
    var isSectionImage: Bool
    var imageName: String
    var sections: [TestSectionType.RawValue : String]
    var correct: String
}

JSON 解码:

func getQuizQuestion() {
        let databaseReference = Database.database().reference().child("allQuiz")
        databaseReference.observeSingleEvent(of: .value) { snapshot in
            do {
                let foo = try FirebaseDecoder().decode(QuizContainer.self, from: snapshot.value ?? "")
                print(foo)
            } catch {
                print(error.localizedDescription)
            }
        }
    }

getQuizQuestion 函数会不会出错?

【问题讨论】:

    标签: swift firebase firebase-realtime-database


    【解决方案1】:

    我解决了我的问题。 我不需要参考。

    func getQuizQuestion() {
            let databaseReference = Database.database().reference() // here
            databaseReference.observeSingleEvent(of: .value) { snapshot in
                do {
                    let foo = try FirebaseDecoder().decode(QuizContainer.self, from: snapshot.value ?? "")
                    print(foo)
                } catch {
                    print(error.localizedDescription)
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2016-10-15
      • 1970-01-01
      • 2020-10-16
      • 2019-07-28
      • 2018-04-06
      • 2020-07-26
      • 2021-11-11
      • 2021-12-04
      相关资源
      最近更新 更多