为什么对象没有被解码? [英] Why is an object not being decoded?

查看:81
本文介绍了为什么对象没有被解码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图调用后端api以获取类型为horse的对象,但在数据中获取了该对象,但是当我尝试对其进行解码时,它将无法正常工作.我该如何解决? 您可以看到我的消息模型和我的马模型.我试图找到它们和json之间的区别,但我找不到.

So I am trying to call backend api to get an object of type horse, I get the object in data but when I try to decode it, it does not work. How can I fix that? You can see my Message Model and my Horse Model. I tried to find a difference between them and the json but I could not.

消息模型

//
//  MessageType.swift
//  HorseStable
//
//  Created by Student on 30/12/2019.
//  Copyright © 2019 smartmobile. All rights reserved.
//

import Foundation

enum MessageType : Int,Decodable {
         case CREATE_HORSE
          case GET_HORSE
          case UPDATE_HORSE
          case DELETE_HORSE
          case GET_HORSES_ASSIGNED_TO_USER
          case REMOVE_HORSE_FROM_USER
          case ADD_HORSE_TO_USER

          /* USERS */
          case CREATE_USER
          case GET_USER
          case UPDATE_USER
          case DELETE_USER

          /* FACILITIES */
          case CREATE_FACILITY
          case GET_FACILITY
          case UPDATE_FACILITY
          case DELETE_FACILITY

          /* STALLS */
          case CREATE_STALL
          case GET_STALL
          case UPDATE_STALL
          case DELETE_STALL

          /* POSTS */
          case CREATE_POST
          case GET_POST
          case UPDATE_POST
          case DELETE_POST

          case ADD_RESERVATION
          case REMOVE_RESERVATION

          case AUTHENTICATE
}


public class Message<T: Decodable> : Decodable {

    var type: MessageType?
    var model : T?
    init(type:MessageType,model:T) {
        self.type = type
        self.model = model
    }

}

马匹模型

  let id: Int?
     let name: String?
     let race: String?
     let lifeNumber : String?
     let chipNumber : String?
     let birthDate : Date?
     let gender : Gender?
     let medicalReports : [MedicalReport]?
     let owners : [User]?


 init (id:Int, name:String,race:String,lifeNumber: String, chipNumber:String, birthDate : Date, gender:Gender, medicalReports: [MedicalReport] , owners : [User]) {

      self.id = id
      self.name = name
      self.race = race
      self.lifeNumber = lifeNumber
      self.chipNumber = chipNumber
      self.birthDate = birthDate
      self.gender = gender


      self.medicalReports = medicalReports
      self.owners = owners

  }

这是我的JSON响应:

Here is my JSON response:

{"type":"GET_HORSE","model":{"id":1,"name":"Horse2","race":"Race2","lifeNumber":"lifenumber2","chipNumber":"chipnumber2","birthDate":1579182813067,"gender":"MALE","medicalReports":[],"owners":[]}}

这是代码

func getJSON (completion: @escaping (Message<Horse>)->()) {
        let url = "http://localhost:8083/horse/1"
    if let url = URL(string: url)
    {
        let task = session.dataTask(with: url) { data, response, error in

                  if error != nil || data == nil {
                      print("Client error!")
                      return
                  }
            let str = String(decoding: data!, as: UTF8.self)
            print(str)
                  do {
                   let decoder = JSONDecoder()
                   print("nothing")

                    if let json = try? decoder.decode(Message<Horse>.self, from: data!) {
                       print(json)
                       print("something")
                   }

                  } catch {
                      print("JSON error: \(error.localizedDescription)")
                  }
              }

              task.resume()
        print("finished")
    }

推荐答案

根据您的JSON-"type":"GET_HORSE"-您应将enum MessageType : Int,Decodable更改为enum MessageType: String, Decodable.更改为String后,我已经检查了您的代码,并在这里找到了正确的模型

according to your JSON - "type":"GET_HORSE" - you should change enum MessageType : Int,Decodable to enum MessageType: String, Decodable. I've checked your code after changes to a String and got correct model here

if let json = try? decoder.decode(Message<Horse>.self, from: data!) {
    print(json)
    print("something")
}

但不是json,它是具有Message<Horse>类型的模型

but it's not json, it's a model with Message<Horse> type

这篇关于为什么对象没有被解码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆