Swift 4使用Codable和Realm解码json

时间:2018-01-27 05:22:08

标签: swift realm codable

几个月前,我开始学习如何使用新的可编码,我发布了这个问题Swift 4 decoding json using Codable。现在我正在尝试使用Realm,我已经更改了模型以遵循文档,但我不断得到它不符合可解码的错误。我很失落如何使这项工作。

{
    "success": true,
    "message": "got the locations!",
    "data": {
        "LocationList": [
         {
            "LocID": 1,
            "LocName": "Downtown"
         },
         {
            "LocID": 2,
            "LocName": "Uptown"
         },
         {
            "LocID": 3,
            "LocName": "Midtown"
         }
      ]
   }
}

class Location: Object, Decodable {
    @objc dynamic var success: Bool = true
    let data = List<LocationData>()
}

class LocationData: Object, Decodable {
    let LocationList = List<LocationItem>()
}

class LocationItem: Object, Decodable {
    @objc dynamic var LocID: Int!
    @objc dynamic var LocName: String!
}

1 个答案:

答案 0 :(得分:1)

而不是像这样声明你的列表:

let data = List<LocationData>()
let LocationList = List<LocationItem>()

相反声明他们:

var data = LocationData()
var LocationList = [LocationItem]()

这证实了codable/decodable

<强>更新
我做了一个与你的模型一起测试的测试,试试这个:

struct Location: Decodable {
    let success: Bool
    let message: String
    var data = LocationData()
}

struct LocationData: Decodable {
    var LocationList = [LocationItem]()
}

struct LocationItem: Decodable {
    var LocID: Int
    var LocName: String
}

let json = "{ \"success\": true, \"message\": \"got the locations!\", \"data\": { \"LocationList\": [ { \"LocID\": 1, \"LocName\": \"Downtown\" }, { \"LocID\": 2, \"LocName\": \"Uptown\" }, { \"LocID\": 3, \"LocName\": \"Midtown\" } ] } }"


do {
    let data = Data(json.utf8)
    let decoded = try JSONDecoder().decode(Location.self, from: data)
    print(decoded)
} catch let error {
    print(error)
}

这将输出:

Location(success: true, message: "got the locations!", data: CodableDecodable.LocationData(LocationList: [CodableDecodable.LocationItem(LocID: 1, LocName: "Downtown"), CodableDecodable.LocationItem(LocID: 2, LocName: "Uptown"), CodableDecodable.LocationItem(LocID: 3, LocName: "Midtown")]))

在您的情况下,您的模型应该是:

class Location: Object, Decodable {
    @objc dynamic var success: Bool = true
    var data = LocationData()
}

class LocationData: Object, Decodable {
    var LocationList = [LocationItem]()
}

class LocationItem: Object, Decodable {
    @objc dynamic var LocID: Int!
    @objc dynamic var LocName: String!
}