有人知道如何在swift中解码mysql 'LONGTEXT‘或'TEXT’类型吗?
我使用nodejs从mysql获取数据,并将其公开为REST API,然后从我的swift代码中调用该API。问题是swift不能解码“background”和“notes”,如果我从投票结构中删除这两列,它就可以工作了
数据库表'vote',结构如下:
CREATE TABLE `vote` (
`createdAt` bigint(20) DEFAULT NULL,
`updatedAt` bigint(20) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`thumbnail` varchar(255) DEFAULT NULL,
`background` longtext DEFAULT NULL,
`notes` text,
`amount` double DEFAULT NULL,
`type` varchar(255) DEFAULT NULL,
`highestScore` double DEFAULT NULL,
`category` int(11) DEFAULT NULL,
`user` int(11) DEFAULT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;json格式类似于
[{
"id": 1,
"name": "IQ Test",
"thumbnail": "eddie",
"background": "This is a typical IQ test",
"amount": 33,
"type": "score",
"highestScore": 174
}]我在swift中的代码是:
struct Vote: Codable {
var id: Int
var name: String
var thumbnail: String
var background: String
var notes: String
var amount: Double
var type: String
var highestScore: Double
enum CodingKeys: String, CodingKey {
case id
case name
case thumbnail
case background
case notes
case amount
case type
case highestScore
}}
解码片段如下所示:
if let data = data {
if let votes = try? jsonDecoder.decode([Vote].self, from: data) {
completion(votes)
}
} else {
completion(nil)
}发布于 2020-08-08 20:05:56
嘿,丹尼,我已经运行了你的代码,并得到了如下优化的方法:-
像这样构建模型结构:
// MARK: - CourseElement
struct VoteElement: Codable {
let id: Int?
let name, thumbnail, background: String?
let amount: Int?
let type: String?
let highestScore: Int?
}
typealias Vote = [VoteElement]在网络调用中使用上述结构,如下所示:
if let data = data {
if let votes = try? jsonDecoder.decode(Vote.self, from: data) {
completion(votes)
}
} else {
completion(nil)
}https://stackoverflow.com/questions/63314322
复制相似问题