Java 使用通用基础模型创建模型

我想创建一些具有几乎相同属性的类。示例: 1. A 类,属性:String a、String b、String c、AnObject d 2. B 类,属性:String a、String b、String c、OtherObject d


A类和B类的区别仅在于属性d。


我已经创建了一个类


public class C <T> {

    private String a;

    private String b;

    private String c;

    private T d;

}

那么对于A类


public class A extends C<A> {

    private SomeObject z;

}

对于B类


public class B extends C<B> {

    private OtherObject z;

    private Integer y;

}

然而,当我使用 jackson 将其制作为 JSON 时,它就成为一个问题。A变成这样:


{

    "a": "",

    "b": "",

    "c": "",

    "d": {

        "a": null,

        "b": null,

        "c": null,

        "z": ""

    }

}

我想要实现的是:


{

    "a": "",

    "b": "",

    "c": "",

    "d": {

        "z": ""

    }

}

如何实现这一目标?


慕森卡
浏览 98回答 2
2回答

函数式编程

我在这里可以看到两种可能的解决方案:仅使用没有继承的泛型类或使用没有泛型的继承。类A并B不必扩展类C。这些冗余属性从父类(即 )进入 JSON 表示形式C。&nbsp; &nbsp; public class C <T> {&nbsp; &nbsp; &nbsp; &nbsp; private String a;&nbsp; &nbsp; &nbsp; &nbsp; private String b;&nbsp; &nbsp; &nbsp; &nbsp; private String c;&nbsp; &nbsp; &nbsp; &nbsp; private T d;&nbsp; &nbsp; }&nbsp; &nbsp; public class A {&nbsp; &nbsp; &nbsp; &nbsp; private SomeObject z;&nbsp; &nbsp; }&nbsp; &nbsp; public class B {&nbsp; &nbsp; &nbsp; &nbsp; private OtherObject z;&nbsp; &nbsp; &nbsp; &nbsp; private Integer y;&nbsp; &nbsp; }&nbsp; &nbsp; // example of usage&nbsp; &nbsp; C<A> a = new C<>();&nbsp; &nbsp; a.setD(new A());&nbsp; &nbsp; // and so on&nbsp; &nbsp; C<B> b = new C<>();&nbsp; &nbsp; b.setD(new B());&nbsp; &nbsp; // and so on另一种方法是创建A和B子元素,C在这种情况下,其子元素不必是通用的。&nbsp; &nbsp; @JsonTypeInfo(&nbsp; &nbsp; &nbsp; use = JsonTypeInfo.Id.NAME,&nbsp;&nbsp; &nbsp; &nbsp; include = JsonTypeInfo.As.PROPERTY,&nbsp;&nbsp; &nbsp; &nbsp; property = "type")&nbsp; &nbsp; @JsonSubTypes({&nbsp;&nbsp; &nbsp; &nbsp; @Type(value = A.class, name = "a"),&nbsp;&nbsp; &nbsp; &nbsp; @Type(value = B.class, name = "b")&nbsp;&nbsp; &nbsp; })&nbsp; &nbsp; public class C {&nbsp; &nbsp; &nbsp; &nbsp; private String a;&nbsp; &nbsp; &nbsp; &nbsp; private String b;&nbsp; &nbsp; &nbsp; &nbsp; private String c;&nbsp; &nbsp; }&nbsp; &nbsp; public class A extends C {&nbsp; &nbsp; &nbsp; &nbsp; private SomeObject z;&nbsp; &nbsp; }&nbsp; &nbsp; public class B extends C {&nbsp; &nbsp; &nbsp; &nbsp; private OtherObject z;&nbsp; &nbsp; &nbsp; &nbsp; private Integer y;&nbsp; &nbsp; }&nbsp; &nbsp; // example of usage&nbsp; &nbsp; A a = new A();&nbsp; &nbsp; B b = new B();

慕哥6287543

这很可能是因为您使用泛型的方式而发生的。类 C 包含其子级(私有 T d),因此当您实例化 A 时,您将继承字段 a、b、c 和 A 的另一个实例,该实例也将包含字段 a、b、c。不确定你在这里要做什么,但如果你想解决这个问题,请从 c 中删除泛型(私有 T d)。public class C {&nbsp; &nbsp; private String a;&nbsp; &nbsp; private String b;&nbsp; &nbsp; private String c;}public class A extends C {&nbsp; &nbsp; private SomeObject z;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java