hebertialmeida/ModelGen

JSON Key mapping?

Closed this issue · 3 comments

Does ModelGen support JSON Key to properties mapping?

In the user.json example we see the integer property current_company_id, this snake cased name matches the JSON key but as part of the ModelGen parsing - using the method fixVariableName in Sources/Filters.swift (used in JsonParser+Context.swift) - the name of the variable becomes currentCompanyId as we see in the User.swiftfile:

self.currentCompanyId = try unboxer.unbox(key: "current_company_id")

It would be nice to be able to not use automatic transformation between JSON key and name of variable name. Let's say that I have a json key created_at but I would like to call the property creationDate (even though createdAt is more Swifty of course...) , is that supported? If not, that would be great!

Maybe the name of the JSON Key key be an "attribute" in the Specs, so in the created_at -> creationDate example above the specs would look something like:

  "properties": {
    ...,
    "creationDate": { "type": "string", "format": "date", "json_key": "created_at" },
    ...
   }

Would that be fairly simple to include?

An alternative to the "json_key" "attribute" in the Specs above is maybe an additional file, called "json_mappings.json" or something.

Then the user.json would remain:

  "properties": {
    ...,
    "creationDate": { "type": "string", "format": "date"},
    ...
   }

But it would have a sibling file user_json_mappings.json or something similar:

{
    "creationDate": "created_at"
}

But then we would have code duplication, the value creationDate is now in two places, which is really bad, so the "json_key" attribute is probable to prefer.

Basically, everything you put under properties will be passed to the stencil template.

What you can do is:

spec.json

"properties": {
    ...
    "creationDate": { "type": "string", "format": "date", "json_key": "created_at" },
    ...
}

template.stencil

// Replace any 
{{ property.key }} 
// by 
{% if property.json_key %}{{ property.json_key }}{% else %}{{ property.key }}{% endif %}

Will generate something like this:

self.creationDate =  unboxer.unbox(key: "created_at", formatter: Date.serverDateFormatter())

Anything added on properties JSON will be passed to the spec.properties on the template, plus some additional verifications like the name convention.

For debug purpose just add this to your template and see {{ spec.properties }}.

I did the automatic name conversion to avoid problems and make it easy, but maybe we can add an option to not disable it.

@hebertialmeida wow I forgot to reply you, how rude! Thanks! I will close this one!