ObjectMapper icon indicating copy to clipboard operation
ObjectMapper copied to clipboard

toJSON() not printing dictionary fields.

Open gunhansancar opened this issue 9 years ago • 3 comments

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]"}

gunhansancar avatar May 12 '17 08:05 gunhansancar

Can anyone confirm the issue? Or Do I do something wrong?

Thanks.

gunhansancar avatar May 15 '17 09:05 gunhansancar

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 avatar May 16 '17 03:05 chenkefeng

@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.

gunhansancar avatar May 16 '17 09:05 gunhansancar