I need to create a json structure with all possible keys from a given jackson annotated java class.
Example java class looks like this:
public class Data {
private FieldA fieldA;
private String fieldB;
public FieldA fieldA(FieldA fieldA) {
this.fieldA = fieldA;
return this;
}
@JsonProperty("fieldA")
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public void setFieldA(FieldA fieldA) {
this.fieldA = fieldA;
}
public String fieldB(String fieldB) {
this.fieldB = fieldB;
return this;
}
@JsonProperty("fieldB")
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public void setFieldB(String fieldB) {
this.fieldB = fieldB;
}
}
public class FieldA {
private String moreData1;
private String moreData2;
public String moreData1(String moreData1) {
this.moreData1 = moreData1;
return this;
}
@JsonProperty("moreData1")
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public void setMoreData(String moreData1) {
this.moreData1 = moreData1;
}
public String moreData2(String moreData2) {
this.moreData2 = moreData2;
return this;
}
@JsonProperty("moreData2")
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public void setMoreData(String moreData2) {
this.moreData2 = moreData2;
}
}
The problem is that the container class “data” has many fields, which in turn have many fields again.
There are some conditions which makes it maybe possible.
-
All java classes behave like standard pojos. They all have default a constructor.
-
The last Field which have no further fields can be null. (json values can be null)
-
All Java classes and its fields are jackson annotated
Goal should look like this:
{
"fieldA" : {
"moreData1" : null
"moreData2" : null
},
"fieldB" : null
}
Like a template of the full json model where only “the last” values are missing.
How can this be achieved or is there already a solution out there?
I tryed already with:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
String json = objectMapper.writeValueAsString(new Data());
but this creates only the structure actual given class and its fields and doesn’t go deeper into fields (like it possibly could with default construction)