Deserialize OneOf in two differents classes Java 11

Viewed 155

My question is the following, I can receive a JSON, where inside it can come two types of class "CHANGE" or "WITHDRAW" in the same type of request. Below is an example JSON 1 and JSON 2

JSON 1

{
   "name":"Eduard Jack",
   "change":{
      "agency":"3213"
   }
}

JSON 2

{
   "name":"john Stev",
   "withdraw":{
      "documentNumber":"121212"
   }
}

When I make this request I get a string from json where I make a mapper to convert into an object, in the OPENAPI documentation it tells me that it is oneOf, it can be one or the other, never both together. How can I make the code understand which class to deserialize into in the Java 11?

1 Answers

I think there are multiple ways to do so

This will convert you string into JsonNode where JSON1 is the string provided

JsonNode json = mapper.readTree(JSON1);
if (json.get("withdraw") == null) : //the value of withdraw will be null in JSON1
   JsonParser parser = mapper.treeAsTokens(json);
   Change change= mapper.readValue(parser, Change.class);
else: //the value of withdraw wont be null in
   JsonParser parser = mapper.treeAsTokens(json);
   Withdraw withdraw= mapper.readValue(parser, withdraw.class);
Related