How do you create objects when beforehand you don't know all it's properties?
I want to create a framework which works with 2 files:
- Input JSON file: Your JSON objects in a JSON file.
- Mapping JSON file: The mapping for these JSON objects in a JSON file.
Let's say you receive the following input JSON Person
:
{
"name": "John Snow",
"age": 18,
"country_code": "UK"
}
And you receive another dynamic JSON mapping file which specifies how some properties should be mapped from the Persons
JSON:
{
"source_type": "country_code",
"source_value": "UK",
"destination_type": "country",
"destination_value": "United Kingdom"
}
In this case I want to change the key "country_code" to "country" with the correct value. The Persons JSON has to be changed to:
{
"name": "John Snow",
"age": 18,
"country": "United Kingdom",
}
I can't create a struct which conforms to Codable because the keys of the JSON can be changed from the mapping:
// This won't work.
struct Person: Codable {
var name: String // can be deleted
var age: Int // can be changed to dateOfBirth
var country: String // can be changed to country_code or national_code
}
It's also possible that the mapping asks to combine certain keys to create new properties:
{
"source_type": "name|age",
"source_value": "John Snow|18",
"destination_type": "nameAge",
"destination_value": "John Snow is 18 years old."
}
This would result in the following JSON object:
{
"name": "John Snow",
"age": 18,
"country": "United Kingdom",
"nameAge": "John Snow is 18 years old."
}
As you can see the input JSON can be totally altered by the mapping. This means that you can't predefine your models.
How do you solve this problem in a generic way? I am not asking for the code but I'm curious about the theoretical solution on how to solve this. Currently I create wrappers around dictionaries but this is nearly the same as creating predefined models which take away the whole concept of the generic framework.
Perhaps I have to define some protocol/interface instead of actual implementations? Or work with Generics?