首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ObjectMapper toJson空

ObjectMapper toJson空
EN

Stack Overflow用户
提问于 2017-04-28 21:13:55
回答 2查看 781关注 0票数 2

我试图用ObjectMapper将对象反序列化为JSON字典,但是反序列化函数总是返回空对象。

代码语言:javascript
复制
class TimeEntryContainer: Mappable {

//MARK: Properties
var entry: TimeEntryObject = TimeEntryObject()

//MARK: Initializers
init() {}

init(_ issue: Issue, hours: Double, activityId: Int) {
    self.entry = TimeEntryObject(issue, hours: hours, activityId: activityId)
}

required init?(map: Map) {
    mapping(map: map)
}

//MARK: Private Methods
func mapping(map: Map) {
    entry       <- map["time_entry"]
}    
}

class TimeEntryObject {

//MARK: Properties
var issueId = -1
var projectId = ""
var hours = Double()
var activityId = -1
var comments = ""

//MARK: Initializers
init() {}

init(_ issue: Issue, hours: Double, activityId: Int) {
    self.issueId = issue.id
    self.projectId = issue.project
    self.hours = hours
    self.activityId = activityId
}

required init?(map: Map) {
    mapping(map: map)
}

//MARK: Private functions
func mapping(map: Map) {
    issueId         <- map["issue_id"]
    projectId       <- map["project_id"]
    hours           <- map["hours"]
    activityId      <- map["activity_id"]
    comments        <- map["comments"]
}
}

下面是我填充TimeEntryContainer对象的部分

代码语言:javascript
复制
let timeEntry = TimeEntryContainer()
timeEntry.entry.projectId = (issue?.project)!
timeEntry.entry.activityId = activityId
timeEntry.entry.hours = timeEntered
timeEntry.entry.comments = commentEdit.text ?? ""

let deserialized = Mapper().toJSONString(timeEntry)
print("hours: \(deserialized) ")

即使正确设置了我的timeEntry对象的值,函数Mapper().toJSONString()Mapper().toJSON()甚至timeEntry.toJSON()timeEntry.toJSONString()都返回一个空的JSON对象/字典。我找不到哪里出错了

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-29 00:12:06

您的TimeEntryObject必须是可映射的。您输入了方法,但没有在类声明中声明一致性。

代码语言:javascript
复制
class TimeEntryObject: Mappable 
票数 1
EN

Stack Overflow用户

发布于 2019-11-19 12:03:50

我也有同样的问题,在我的例子中,我已经实现了Mappable协议。我没有映射出类的变量,这给了我空的json。

张贴只是另一种选择/解决方案。可能会在需要的情况下帮助别人。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43688959

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档