3

I used ObjectMapper to map JSON to object and vise versa, I want to convert an object to JSON, but when I try converting the object to JSON, the fields without value, will be deleted from JSON, for example:

class Provider: NSObject, Mappable {

    public var firstName:String?

    public var lastName:String?

    required init?(map: Map){

    }

    override init(){

    }

    func mapping(map: Map) {
        self.firstName <- map["firstName"]
        self.lastName <- map["lastName"]
}

When I call below function it prints a JSON without any key/value:

func printProviderJSON(){

    let provider = Provider()

    let providerDictionary = provider.toJSON()

    let datproviderData = try! JSONSerialization.data(withJSONObject: providerDictionary, options: .prettyPrinted)

    let providerJSON =  NSString(data: datproviderData, encoding: String.Encoding.utf8.rawValue)!

    print(providerJSON) // {}
}

But I need a JSON like this:

{
    "firstName": null,
    "lastName": null
}
Anton Belousov
  • 1,140
  • 15
  • 34
Hamed
  • 1,678
  • 18
  • 30

1 Answers1

4

It solved with one line in mapping function

func mapping(map: Map) {
        map.shouldIncludeNilValues = true
        self.firstName <- map["firstName"]
        self.lastName <- map["lastName"]
    }
Hamed
  • 1,678
  • 18
  • 30