I'm running into the following problem when trying to execute a POST call using Jersey and Genson:
.... com.owlike.genson.JsonBindingException: No constructor has been found for type interface Animal ....
I have the following setup:
-> Animal.java
package com.test;
import org.codehaus.jackson.annotate.JsonSubTypes;
import org.codehaus.jackson.annotate.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes( {@JsonSubTypes.Type(value = Dog.class, name = "dog") })
public interface Animal
{ }
-> Dog.java
package com.test;
import org.codehaus.jackson.annotate.JsonTypeName;
import org.codehaus.jackson.annotate.JsonProperty;
@JsonTypeName("dog")
public class Dog implements Animal
{
@JsonProperty
public String name;
public String getName() { return name; }
public void setName(String n) { this.name = n; }
}
-> Zoo.java
package com.test;
import java.util.List;
public class Zoo
{
private List<Animal> animals;
public List<Animal> getAnimals()
{
return animals;
}
public void setAnimals(List<Animal> animals)
{
this.animals = animals;
}
}
-> GensonCustomResolver.java
package com.test;
import javax.ws.rs.next.ContextResolver;
import javax.ws.rs.next.Provider;
import com.owlike.genson.Genson;
@Provider
public class GensonCustomResolver implements ContextResolver<Genson>
{
private final Genson genson = new Genson.Builder().useRuntimeType(true).useClassMetadata(true).create();
@Override
public Genson getContext(Class<?> arg0)
{
return genson;
}
}
-> JerseyService.java
package com.test;
import javax.ws.rs.*;
import org.codehaus.jackson.*;
@Path("/exampleservice")
public class JerseyService
{
@POST
@Path("somePath")
@Consumer(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Zoo createAnotherZoo(Zoo zoo) throws JsonParseException, JsonMappingException, Exception
{
Zoo newZoo = new Zoo();
Collection<Animal> animals = zoo.getAnimals();
List<Animal> newAnimals = new ArrayList<Animal>();
for (Animal a : animals) {
Dog dog_a = (Dog) a;
Dog dog_b = new Dog();
dog_b.setName(dog_a.getName() + "TEST");
newAnimals.add(dog_b);
}
newZoo.add(newAnimals);
return newZoo;
}
}
The input JSON looks like this:
{
"animals" : [
{
"name": "Unno"
}
]
}
To summarize, I have a List and I'm trying to use one of the interface implementations when deserializing my objects.
Thank you in advance.
::::SOLUTION:::::
In case anyone runs into this:
I removed genson dependencies completely as suggested below. Only used jackson annotations and it seemed to work. Also I removed the @JsonProperty from the name attribute in the Dog.java.
Thank you :) :)