带有继承和方法重载的杰克逊序列化问题

问题描述 投票:0回答:1

我在RESTful应用程序中使用Jackson和Jersey + Jetty。杰克逊库为:jackson-annoations-2.8.0 jackson-core-2.8.9jackson-databind-2.8.9

我无法让Jackson输出子类的值。它总是输出继承类的值。尽管我明确提供了具体对象。该场景很难正确表达,希望下面的示例能更好地解释它。

这里是要序列化的类的伪代码:

  • Parent0.java:

    class Parent0 {
      protected Child0 child;
    
      public Parent0() {}
    
      public Child0 getChild() {
         return child;
      }
    
      public void setChild(Child0 child) {
         this.child = child;
      }
    }
    
  • Parent1.java:

    class Parent1 extends Parent0 {}
    
  • Child0.java:

    class Child0 {
      protected int id;
    
      public Child0() {}
    
      public void setId(int id) {
         this.id = id;
      }
    
      public int getId() {
         return this.id;
       }
    
       @Override
       public boolean equals(Object o) {
          if (this == o) return true;
          if (o == null || getClass() != o.getClass()) return false;
          Child0 child0 = (Child0) o;
          return id == child0.id;
       }
    
       @Override
       public int hashCode() {
          return Objects.hash(id);
       }
    }
    
  • Child1.java:

    class Child1 extends Child0 {
       private String childName;
    
       public Child1() {}
    
       public String getChildName() {
          return childName;
        }
    
        public void setChildName(String childName) {
           this.childName = childName;
        }    
    }
    
  • 在主控制器内部:

    Parent0 p0 = new Parent0();
    Child0 c0 = new Child0();
    c0.setId(0);
    p0.setChild(c0);
    
    Parent0 p1 = new Parent1();
    Child1 c1 = new Child1();
    c1.setId(1);
    c1.setChildName("C1");
    p1.setChild(c1);
    
    serializeAndPrint(p0); // #1
    serializeAndPrint(p1); // #2
    

输出:

    #1 Parent0.json
    {
        child: {
            id: 0
        }
    }

    #2 Parent1.json
    {
        child: {
            id: 1
        }
    }

预期:

    #2 Parent1.json
    {
        child: {
            id: 1,
            childName: "C1"
        }
    }
java json serialization jackson jersey
1个回答
0
投票

您的serializeAndPrint方法的实现是什么?我编写了一个单元测试来重现该问题:

public class JsonTest {

@Test
public void test() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();

    Parent0 p0 = new Parent0();
    Child0 c0 = new Child0();
    c0.setId(0);
    p0.setChild(c0);

    Parent0 p1 = new Parent1();
    Child1 c1 = new Child1();
    c1.setId(1);
    c1.setChildName("C1");
    p1.setChild(c1);

    System.out.println(mapper.writer(new DefaultPrettyPrinter()).writeValueAsString(p0));
    System.out.println(mapper.writer(new DefaultPrettyPrinter()).writeValueAsString(p1));

}

}

输出正是您所期望的:

{
  "child" : {
  "id" : 0
  }
}
{
  "child" : {
   "id" : 1,
   "childName" : "C1"
   } 
}
© www.soinside.com 2019 - 2024. All rights reserved.