Spring JSON 将 class 属性 动态地转换为其他 class

Spring JSON cast class property to other class dynamically

我有一个(更多)实体,它有一个 UserEntity class(创建者)。 等:

@Entity 
class TestEntity {

@ManyToOne
private UserEntity creator;


}

现在,在 UserEntity 上我有很多字段,在某些请求中使用它并不重要。 我创建了一个 class(只有重要字段的 UserEntityMiniFied),它有一个带有 UserEntity 的构造函数,

好吧,我可以用一个 json 注释动态地解决这个问题吗,我的意思是, 我试试:

@JsonView(UserEntityMinified.class)
private UserEntity creator;

但它不起作用。

感谢您的帮助。

我可以说你走在正确的轨道上。

首先 – 让我们来看一个简单的例子 – serialize an object with @JsonView.

这是我们的观点:

public interface JSONView {
    interface JSONBasicView {}
    interface JSONAdvancedView extends JSONBasicView {}
}

UserEntity 实体:

@Entity
class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonView(JSONView.JSONBasicView.class)
    private int id;

    @JsonView(JSONView.JSONBasicView.class)
    private String name;

    @JsonView(JSONView.JSONBasicView.class)
    private String age;

    @JsonView(JSONView.JSONAdvancedView.class)
    private String country;

    @JsonView(JSONView.JSONAdvancedView.class)
    private String city;

    public UserEntity() {
    }

    // getter/setter ..
}

TestEntity 实体:

@Entity
class TestEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonView(JSONView.JSONBasicView.class)
    private int id;

    @JsonView(JSONView.JSONBasicView.class)
    private String name;

    @ManyToOne
    @JsonView(JSONView.JSONBasicView.class)
    private UserEntity userEntity;

    public TestEntity() {
    }

    // getter/setter ..
}

现在让我们使用我们的视图序列化一个 TestEntity 实例:

public static void main(String[] args) {

    UserEntity userEntity = new UserEntity();
    userEntity.setId(1);
    userEntity.setName("User Entity Name");
    userEntity.setAge("33");
    userEntity.setCountry("Country");
    userEntity.setCity("City");

    TestEntity testEntity = new TestEntity();
    testEntity.setId(1);
    testEntity.setName("Test Entity Name");
    testEntity.setOtherTestEntity(userEntity);

    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);

    String basicView = mapper
            .writerWithView(JSONView.JSONBasicView.class)
            .writeValueAsString(testEntity);
    System.out.println(basicView);

    String advancedView = mapper
            .writerWithView(JSONView.JSONAdvancedView.class)
            .writeValueAsString(testEntity);
    System.out.println(advancedView);
}

此代码的输出将是:

// JSONBasicView
{
  "id": 1,
  "name": "Test Entity Name",
  "userEntity": {
    "id": 1,
    "name": "User Entity Name",
    "age": "33"
  }
}

// JSONAdvancedView
{
  "id": 1,
  "name": "Test Entity Name",
  "userEntity": {
    "id": 1,
    "name": "User Entity Name",
    "age": "33",
    "country": "Country",
    "city": "City"
  }
}

您还可以check here做更多事情。