alibaba / HandyJSON

A handy swift json-object serialization/deserialization library
Other
4.22k stars 615 forks source link

Is there a root key for deserialization (HelpingMapper / mapping)? #489

Open SebastianCiuca opened 4 months ago

SebastianCiuca commented 4 months ago

I'm trying to tidy up a model, and I'm attempting to gather a few properties into a structure. Basically, I'm trying to "pull" a few properties up a level. The problem is that, because the key for 'graphics' doesn't exist in the JSON (see examples below), the mapper won't even execute the TransformOf decoder (edit: this is my assumption).

Is there a key that maps to the main / entire JSON so that I can deserialize from that?

Is there another way for me to achieve this?

JSON example:

{
  "structure": {
    "imagePath": "somePath",
    "colorCode": "someCode"
  },
 "count": 20
}

Struct example:

struct Graphics: HandyJSON {
  var imagePath: String = ""
  var color: String = ""
  var code: Int = 0

  mutating func mapping(mapper: HelpingMapper) {
      mapper <<<
            color <-- "structure.colorCode"
      mapper <<<
            imagePath <-- "structure.imagePath"
    }
}

struct MainModel: HandyJSON {
  var graphics = Graphics() 

  mutating func mapping(mapper: HelpingMapper) {
    mapper <<<
          graphics <-- TransformOf(
                  fromJSON: {                      
                          Page.Graphics.deserialize(from: $0)
                  },
                  toJSON: { _ in [:] }
              )
  }
}

What I meant by

a key that maps to the main / entire JSON

is something like:

graphics <-- ("mainJSONKey", TransformOf(
                  fromJSON: {                      
                          Page.Graphics.deserialize(from: $0)
                  },
                  toJSON: { _ in [:] }
              ))

Also tried the following, without success:

mapper <<<
    graphics.imagePath <-- "structure.imagePath"