There is a function which returns a JSON formatted list of elements. Problem occurs when reading content from a result which contains element of descendant type.
As an example, consider the following definitions:
public class Fruits {
public String description;
public List<Fruit> fruits = new ArrayList<Fruit>();
}
public class Fruit {
public String name;
public int pieces;
}
public class Banana extends Fruit {
public String origin;
}
@ApplicationScoped
@Provider
@Produces("application/json")
@Path("/fruit")
public class MyRestService {
@GET
@Path("/fruits")
public Fruits getFruits() {
Fruits myFruits = new Fruits();
myFruits.description = "My fruits";
Fruit myApple = new Fruit();
myApple.name = "apple";
myApple.pieces = 8;
myFruits.fruits.add(myApple);
Banana myBanana = new Banana();
myBanana.name = "banana";
myBanana.pieces = 5;
myBanana.origin = "Ecuador";
myFruits.fruits.add(myBanana);
return myFruits;
}
}
The resulting JSON is the following:
{
"description":"My fruits",
"fruits":[
{
"name":"apple",
"pieces":8
},
{
"name":"banana",
"pieces":5,
"origin":"Ecuador"
}
]
}
Suppose we have this result in the content
variable. I want to parse it as follows:
ObjectMapper objectMapper = new ObjectMapper();
Fruits fruits = objectMapper.readValue(content, Fruits.class);
The following exception is thrown:
Exception in thread "main" org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "origin" (Class myresttest.Fruit), not marked as ignorable
at [Source: java.io.StringReader@38653ad5; line: 1, column: 104] (through reference chain: myresttest.Fruits["fruits"]->myresttest.Fruit["origin"])
Is it somehow possible to overcome this problem, without touching the server code?