'Alternative to Jackson @JsonSubTypes in python?
Instead of using a dict to store and pass data we are going completely OOPS approach of storing the data as class attributes. In our json the input and output structure can change.
In JAVA we have jackson library where we can based on json key specify the class
Example:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = S1Config.class, name = "S1")}
@JsonSubTypes.Type(value = S2Config.class, name = "S2")}
)
Wanted to do similar thing in Python and only thing I could think was to use if conditions
class DataModel:
def __init__(self, data):
if data["in"]["type"] == "s1":
self.input = S1Config(data["input"])
elif data["in"]["type"] == "s2":
self.input = S2Config(data["input"])
if data["out"]["type"] == "s1":
self.output = S1Config(data["output"])
Is there any other better way then what I have implemented?
Solution 1:[1]
It might be clearer to use some kind of mapping.
Here is the example
in_out_mappings = {
's1': S1Config,
's2': S2Config,
}
class DataModel:
def __init__(self, data):
in_type = data['in']['type']
in_class = in_out_mappings[in_type]
out_type = data['out']['type']
out_class = in_out_mappings[out_type]
self.input = input_class(data['input'])
self.output = output_class(data['output'])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex Kosh |
