tristanhimmelman / ObjectMapper

Simple JSON Object mapping written in Swift
MIT License
9.14k stars 1.03k forks source link

How to send whole JSON data to custom transform? #994

Open atoami opened 6 years ago

atoami commented 6 years ago

I want to send whole JSON data to custom transform. But it sends only one property(title in my example code). How can I send the whole data?

Your JSON dictionary:

    {
      "tile_details": [
        {
          "container_uuid": "8aca70c0-8740-469a-96ab-8ca60a0db05e",
          "content": "TEXT",
          "created_by": "dd7d5169-f70e-4c25-9695-4a7fd1925507",
          "interaction_type": "none",
          "type": "text",
          "uuid": "895a1748-71c3-4af5-a50d-28f4610b894d"
        },
        {
          "container_uuid": "8aca70c0-8740-469a-96ab-8ca60a0db05e",
          "content": "IMAGE",
          "created_by": "dd7d5169-f70e-4c25-9695-4a7fd1925507",
          "interaction_type": "none",
          "type": "single-image",
          "uuid": "b03994bf-47a1-4d3a-af00-6c5d04091af0"
        }
      ],
      "uuids": [
        "UUID1",
        "UUID2"
      ],
      "title": "TITLE",
      "uuid": "8aca70c0-8740-469a-96ab-8ca60a0db05e"
    }

Your model:

class PostTilesTransform: TransformType {
    typealias Object = [Tile]

    public init() {}

    public func transformFromJSON(_ value: Any?) -> [Tile]? {
        print(value.debugDescription) // I want to see the whole JSON data
        print(type(of: value!)) // I want to see JSON data type's name
        return []
    }

    public func transformToJSON(_ value: [Tile]?) -> JSON? {
        return nil
    }
}
struct Post: Mappable {

    var uuid: String = ""
    var title: String = "No title"
    var tiles: [Tile] = []

    init?(map: Map) {}

    // Mappable
    mutating func mapping(map: Map) {
        uuid                <- map["uuid"]
        title               <- map["title"]
        tiles               <- (map, PostTilesTransform())
    }
}

What you did:

let repo = Mapper<Post>().map(myJSONDictionary)

What you expected:

I exepected something like:

    public func transformFromJSON(_ value: Any?) -> [Tile]? {
        print(value.debugDescription) // I want to see the whole JSON data
        print(type(of: value!)) // I want to see JSON data type
        return []
    }

What you got:

    public func transformFromJSON(_ value: Any?) -> [Tile]? {
        print(value.debugDescription) // This prints title - `TITLE`
        print(type(of: value!)) // This prints String type's name
        return []
    }

So this means that following line sends only title, not whole data.

tiles               <- (map, PostTilesTransform())
nicopuri commented 6 years ago

@wagng Any update? I want to do exactly what you need.