尝试使用 Jersey 和 Genson 执行 POST 调用时遇到以下问题:
.... com.owlike.genson.JsonBindingException: No constructor has found for type interface 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
{ }
-> 狗.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; }
}
-> 动物园.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;
}
}
输入 JSON 如下所示:
{
"animals" : [
{
"name": "Unno"
}
]
}
总而言之,我有一个列表,并且在反序列化对象时尝试使用其中一种接口实现。
先感谢您。
::::解决方案:::::
万一有人遇到这种情况:
我完全删除了genson依赖项,如下所示。只使用杰克逊注释,它似乎工作。我还从 Dog.java 的 name 属性中删除了 @JsonProperty。
谢谢 :) :)