ObjectMapper
ObjectMapper copied to clipboard
toJSON() not printing dictionary fields.
I'm using the ObjectMapper(2.2.6 latest) version
Also tried [String:String] instead of Dictionary<String, String>
Your model:
struct User: Mappable {
var name: String?
var email: String?
var detailMap: Dictionary<String, String>?
init() {}
init(_ map: Map) {
name <- map["name"]
email <- map["email"]
detailMap <- map["detailMap"]
}
}
What you did:
var user = User()
user.name = "name1"
user.email = "[email protected]"
user.detailMap = ["mykey":"myvalue"]
print("user:\(user)")
print("json:\(user.toJSONString() ?? "")")
What you expected:
I exepected something like:
json:{"name":"name1","email":"[email protected]", "detailMap" : { "mykey" : "myvalue" }}
What you got:
user:User(name: Optional("name1"), email: Optional("[email protected]"), detailMap: Optional(["mykey": "myvalue"]))
json:{"name":"name1","email":"[email protected]"}
Can anyone confirm the issue? Or Do I do something wrong?
Thanks.
I tried, and this is good!
Example:
struct User: Mappable {
var name = ""
var dict = [String:Any]()
init() {}
init?(map: Map) {
}
mutating func mapping(map: Map) {
name <- map["name"]
dict <- map["dict"]
}
}
var u = User()
u.name = "test"
u.dict = ["key1":"value1", "key2": "value2"]
guard let jsonString = u.toJSONString() else {return}
print(jsonString)
/////{"dict":{"key2":"value2","key1":"value1"},"name":"test"}
@chenkefeng Thanks for your response.
I discovered my issue. Sometimes we overlook the situation and miss simple stuff.
In my actual implementation I have 10 or more fields. And I missed the mapping for the dictionary
dict <- map["dict"]
That is why it doesn't convert that field to JSON string.
Thank you.