Issue
I get a response from the service. It could be as follows:
{
"uid": "f12c394f-5cb7-48b8-bfa5-17d248df4866",
"data": [
{
"vac_status": "1",
"vaccination_date": "2021-03-16",
"lastname": "lastname",
"firstname": "firstname",
"birth_date": "1993-12-01",
"gender": "1"
}
]
}
Or it could be this.
{
"uid": "f12c394f-5cb7-48b8-bfa5-17d248df4866",
"data": [
{
"cov_status": "2",
"disease_outcome_date": "2021-05-19",
"lastname": "lastname",
"firstname": "firstname",
"birth_date": "1973-02-01",
"gender": "1"
}
]
}
Is there any way I can check what I got? I came up with only to look for matches in the string. (I take the query as a string and look for the words "vac" or "cov") I think this is not the right approach. Also, I don't know how to properly deserialize if I don't know what came to me. I don't know what type came to me.
Solution
You can use the Jackson DEDUCTION
mathod of identifying the classes it is deserialising.
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
public class ParseExample {
static class Status {
public String gender;
public String birth_date;
public String firstname;
public String lastname;
}
static class VacStatus extends Status {
public String vac_status;
public String vaccination_date;
}
static class DiseaseStatus extends Status{
public String cov_status;
public String disease_outcome_date;
}
static class Response {
public String uid;
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
@JsonSubTypes({
@JsonSubTypes.Type(VacStatus.class),
@JsonSubTypes.Type(DiseaseStatus.class)})
public List<Status> data;
}
public static void main(String... args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonParser parser = mapper.createParser(ParseExample.class.getClassLoader().getResourceAsStream("test2.json"));
Response w = parser.readValueAs(new TypeReference<Response>() {});
parser = mapper.createParser(ParseExample.class.getClassLoader().getResourceAsStream("test3.json"));
Response w2 = parser.readValueAs(new TypeReference<Response>() {});
}
}
test2.json
and test3.json
are your examples above.
Answered By - tgdavies
Answer Checked By - David Marino (JavaFixing Volunteer)