5

So I have a simple class like the following:

class User: NSObject {

  var name = ""
  var phoneNumber = ""

  override func mapping(map: Map) {
    super.mapping(map)
    name          <- map["name"]
    phoneNumber   <- map["phoneNumber"]
  }

}

This works great when turning a JSON response that contains these fields into an object. However i would like to exclude a field when serializing back to JSON. How can I do that? Let's say I would only like to send name and omit phoneNumber. Is this possible? Seems like a pretty reasonable use case, but I haven't managed to find a solution .

Julian B.
  • 3,605
  • 2
  • 29
  • 38

1 Answers1

6

Yes it is possible, you could use MappingType enum to handle this. It has two values FromJSON and ToJSON which you could use to create logic to map your object.

override func mapping(map: Map) {
    super.mapping(map)
    if map.mappingType == MappingType.FromJSON {
        name          <- map["name"]
        phoneNumber   <- map["phoneNumber"]
    } else {
        name          <- map["name"]
    }
}
seto nugroho
  • 1,359
  • 1
  • 13
  • 20
  • wow this is exactly what i needed!!! thanks so much. where the hell is that in the docs? i swear i didn't see it anywhere. – Julian B. Aug 23 '16 at 00:54
  • i'm not sure if this is in docs, i found it few months ago when i want to do exactly like your scenario and play with its properties. – seto nugroho Aug 23 '16 at 01:07