Search code examples
jsonswiftmodelmappermoya

Mapping JSON response to objects using Rx programming Moya


I am trying to use the mapObject function of the ModelMapper library like this :

return provider.request(API.userInfo(userId: API.userId))
            .mapObject(type: UserTest.self, keyPath: "user")

with this Json :

{
    "success": true,
    "user": {
        "_id": "HJzCZaXEW",
        "mail": "Valentin",
        "__v": 0,
        "bikes": [
            "S1rjHamNZ",
            "HkxhHpXEZ"
        ],
        "updated": "2017-06-30T12:19:22.016Z",
        "created": "2017-06-30T12:19:22.015Z"
    }
}

I have tried to see what's the error using this way :

API.getUserInfo()
        .subscribe {event in
            switch event {
            case .next(let response):
                print(response)
            case .error(let error):
                print("error")
                print(error)
            default:
                print("default")
            }
        }

and I got this in my console :

error
jsonMapping(Status Code: 200, Data Length: 177)

and this is my mapping structure :

import Mapper

struct UserTest: Mappable {
    var name: String
    var lastname: String
    var mail: String
    var bikes: [String]

    init(map: Mapper) throws {
        try name = map.from("name")
        try lastname = map.from("lastname")
        try mail = map.from("mail")
        try bikes = map.from("bikes")
    }
}

I have also tried an pod update but nothing has changed. I really don't understand why it's not working.

Thanks in advance for your help!


Solution

  • The problem is at these lines

    try name = map.from("name")
    try lastname = map.from("lastname")
    

    Your json data does not have these two key, "name" and "lastname". Try remove these two lines or make both as "optional" if the data maybe null or exist

    lastname = map.optionalFrom("lastname")