Steve Chambers Steve Chambers - 1 month ago 12
Java Question

How to get all Jackson/JAXB annotated property values?

Given an entity (model) class with Jackson annotations for setting column names:

public class GridRowModel {
private Long maxRegulatedValue;

@JsonProperty(value="Max Regulated Value")
public Long getMaxRegulatedValue() {
return maxRegulatedValue;
}

@JsonProperty(value="Fares")
public Map<String, FareModel> getFares() {
return fares;
}
...


(Could alternatively have used JAXB annotations - e.g. @XmlElement(name="Max Regulated Value").

I need a
getGridColumns
method that will return a JSON structure with all the column names extracted from this model + its submodels (so here it would return "Max Regulated Value" and all
@JsonProperty
values from
FareModel
.)

The question is how best to approach this? Have mooted using reflection, e.g. something like
method.getAnnotation(JsonProperty.class).value())
but not sure if this would even work and it doesn't seem ideal. For one thing, it wouldn't respect the order specified by
@JsonPropertyOrder
(or
propOrder
in JAXB). Am wondering if there is a smarter way (perhaps using some kind of Adapter?)

Answer

In the end, the column order turned out to be important so I annotated each model class with:

@JsonPropertyOrder({ "Max Regulated Value", "Another field", ... })

...and then wrote a method to loop through these (using reflection) + the submodel (which is actually fixed).