'Java + JSON: list of anonymous objects (key + value) with different key names
Maybe it's simple, but I'm stuck... I have an app using Spring Boot and springframework.web.client.RestTemplate, so there's Jackson on backseat doing JSON job automatically.
I want to deserialize REST input with JSON like this:
{
"serial_no": 12345678,
"last_dt": [
{
"lp": "2022-04-22T15:00:00"
},
{
"bp": null
},
{
"dp": "2022-04-22T00:00:00"
},
{
"iv": "2022-04-22T00:05:11"
}
]
}
Please, help me to create POJO for this model... If I created following classes (simplified with lombok):
@Data
public class LastDt {
@JsonProperty("lp")
private String lp;
@JsonProperty("bp")
private String bp;
@JsonProperty("dp")
private String dp;
@JsonProperty("iv")
private String iv;
}
@Data
public class Device {
@JsonProperty("serial_no")
private Long serialNo;
@JsonProperty("last_dt")
private List<LastDt> lastDt;
}
deserialization is technically ok - I got an object with serialNo Long value and unfortunatelly list of 4 instances of class LastDt: first instance (lastDt[0]) had field "lp" with value and "bp", "dp", "iv" null; second (lastDt[1]): "bp" with value and "lp", "dp", "iv" null and so on - only one value was set and others are not. That's far from what I want to get. As you can see, there's four pair-like anonymous objects with different key names, so my model is bad, and I know this, but got stuck trying to create other ones... Can anyone help me?
Solution 1:[1]
You can use @JsonAlias. The idea is to have a single field in LastDt
, with all possible names of the property mapped to that field.
public class LastDt {
@JsonAlias({"lp", "bp", "dp", "iv"})
private String value;
//getter and setters
@Override
public String toString() {
return "LastDt{" +
"value='" + value + '\'' +
'}';
}
}
No changes are required to Device
.
And a simple test:
public class Temp {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
InputStream dataStream = getTheStream();
Device device = mapper.readValue(dataStream, Device.class);
System.out.println(device);
}
}
Solution 2:[2]
You should use @JsonInclude(JsonInclude.Include.NON_NULL)
in your class:
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LastDt {
@JsonProperty("lp")
private String lp;
@JsonProperty("bp")
private String bp;
@JsonProperty("dp")
private String dp;
@JsonProperty("iv")
private String iv;
}
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 | Chaosfire |
Solution 2 |