I need to serialize and send several equal objects but with different key names which depend on amount number of them
{
"object1": {
"name": "random",
"pass": true
},
"object2": {
"name": "random",
"pass": false
},
"object3": {
"name": "random",
"pass": true
}
}
I use Lombok @Builder + Jackson @JsonProperty for body models describing to be sent but have no ideas how to handle the case when the same object might be added several times with numeric increasing key name without code duplication as at an example below.
@Builder
public class Sample {
@JsonProperty("object1")
private RandomObject object1;
@JsonProperty("object2")
private RandomObject object2;
@JsonProperty("object3")
private RandomObject object3;
}
You can do this,
public class Sample {
Map<String, RandomObject> objects = new HashMap<>();
public void add(String key, RandomObject val) {
objects.put(key, val);
}
@JsonAnyGetter
public Map<String, RandomObject> getObjects() {
return objects;
}
}
You can crate the response like this,
RandomObject object1 = RandomObject.builder().name("John").pass(true).build();
RandomObject object2 = RandomObject.builder().name("Jane").pass(false).build();
Sample sample = new Sample();
sample.add("object1", object1);
sample.add("object2", object2);
return sample;
Please also note that you can skip creating this Simple
object and crate Map and return it as your response.