bmoliveira / Moya-ObjectMapper

ObjectMapper bindings for Moya and RxSwift
MIT License
492 stars 172 forks source link

Posting object Invalid type in JSON write #83

Closed burniejm closed 6 years ago

burniejm commented 6 years ago

I am trying to post a mapped model that I am newing up myself. My model originally only had the init?(map: Map) method but I added another init() {} so I could new one up and set its values before posting it. However, when I do this I get

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write

Do I have to use the map init method? If so what do I pass it?

Here is my model

import Foundation
import ObjectMapper

public class Office: Mappable {
    var id: Int = 0
    var status: String?
    var name: String?
    var addressLine1: String?
    var addressLine2: String?
    var addressLine3: String?
    var city: String?
    var state: String?
    var postalCode: String?
    var country: String?

    init() { }

    public required init?(map: Map) { }

    public func mapping(map: Map) {
        id <- map["id"]
        status <- map["status"]
        name <- map["name"]
        addressLine1 <- map["address_line1"]
        addressLine2 <- map["address_line2"]
        addressLine3 <- map["address_line3"]
        city <- map["city"]
        state <- map["state"]
        postalCode <- map["postal_code"]
        country <- map["country"]
    }
}

And my new office

let newOffice = Office()
newOffice.name = "test"
newOffice.addressLine1 = "test"
newOffice.addressLine2 = "test"
newOffice.postalCode = "test"

Posting my office

self.provider!
            .request(.postOffice(office: newOffice)) { result in
                switch result {
                case let .success(response):
                    do {
                        try _ = response.filterSuccessfulStatusCodes()

                        let office = try response.mapObject(Office.self)
                        success(office)
                    } catch {
                        do{
                            let apiError = try response.mapObject(APIError.self)
                            failure(apiError.friendlyDisplay())
                        } catch {
                            failure("Creating New Office Failed")
                        }
                    }
                case let .failure(error):
                    failure("Post Office Failed")
                }
        }

My Task

public var task: Task {
        switch self {

        case let .postOffice(office):
            return .requestParameters(parameters: ["office": office], encoding: JSONEncoding.default)

        default:
            return .requestPlain
        }
    }
pratyushpratik commented 6 years ago

did you find the solution?