泽西杰克逊不会序列化子类

时间:2018-02-08 06:25:28

标签: java json jackson jersey jersey-2.0

您好我正在使用Jersey创建一个宁静的服务。要返回结果,我需要转换为json格式。我有一个父类和子类,其中只发送父类值,但子类没有被序列化。

父类 -

@JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({@JsonSubTypes.Type(value = Child.class)})
public abstract class Parent {
    private String test = "hello";

    public Parent () {
    }
    public Parent (String test) {
     this.test = test;
    }
    public String getTest() {
        return test;
    }    
    public void setTest(String test) {
        this.test = test;
    }

儿童班 -

public class Child extends Parent{
   private String name;

   public Child() {
       super();
   }
   public Contact(String name, String test) {
      super(test);
      this.name = name;
   }
   public String getName() {
      return name;
   }    
   public void setName(String name) {
      this.name = name;
   }
}

实际班级 -

public class RestResponse {
    private List<Parent> result;
    // default and one argument constructor...

    public List<Parent> getResult() {
        return result;
    }    
    public void setResult(List<Parent> result) {
        this.result= result;
    }
}

休息控制器 -

@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/testJson")
public class MyRestController {



      @GET
      @Path("/search")
     public RestResponse getContacts(@Context HttpHeaders headers) throws URISyntaxException {
       Parent p = new Child("myName", "testString");
       List<Parent> parentList = new ArrayList<Parent>();
       parentList.add(p);
       RestResponse resultResponse = new RestResponse();
       resultResponse .setData(parentList );
       return resultResponse; 
}

但下面是我得到的结果,

{
    "result": [
        {
            "test": "testString"
        }
    ]
}

子类的属性名称未序列化。我尝试了Jersey and Jackson serialization of subclasses does not include extra attributes中给出的解决方案,但我仍然看到子类属性没有被转换。

任何帮助都将非常感激。提前谢谢。

0 个答案:

没有答案