在来自应用程序.yml的json响应中包含/排除属性

cmssoen2  于 2022-12-30  发布在  其他
关注(0)|答案(3)|浏览(127)

我正在使用JHipster(Spring Boot )来生成我的项目。我想隐藏/显示来自application. yml的JSON字段。例如:
我有下面的类

@Entity
@Table(name = "port")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Port implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id")
    private Long id;

    @Column(name = "city")
    private String city;

    @Column(name = "description")
    private String description;

    //getters & setters
}

我的GET方法返回如下响应:

{
"id": 1,
"city": "boston",
"description": "test test"
}

我希望能够包括/排除一些字段从应用程序.yml(因为我没有application.properties)否则有这样的东西:

//application.yml

include: ['city']
exclude: ['description']

在这个例子中,我json应该看起来像:

{
"id": 1,
"city": "boston",
}

例如,如果我有40个字段,我需要隐藏10个并显示30个,我只想把我想隐藏的10个字段放在application.yml的exclude中,而不是每次都更改代码。我猜@jsonignore隐藏字段,但我不知道如何从application.yml中执行此操作
抱歉,我没解释清楚。我希望你能说清楚。
提前感谢您的任何建议或解决方案做类似的事情

wsxa1bj1

wsxa1bj11#

Sping Boot 默认使用JacksonJSON库将你的类序列化为Json。在这个库中有一个注解@JsonIgnore,它的作用就是告诉Json引擎忽略序列化/反序列化的特定属性。因此,假设在你的实体Port中,你想从显示中排除属性city,你所要做的就是注解这个属性(或其getter方法),并带有@JsonIgnore注解:

@Column(name = "city")
@JsonIgnore
private String city;
bf1o4zei

bf1o4zei2#

您可以尝试在控制器中创建散列表来管理HTTP响应。

Map<String, Object> map = new HashMap<>();

        map.put("id", Port.getId());
        map.put("city", Port.getCity());

        return map;
jyztefdp

jyztefdp3#

基本上,您不会在REST控制器中公开Port实体,而是使用一个简单的类(例如PortMapper)在服务层中公开一个您从实体中取值的DTO(数据传输对象)。PortDTO也可以是Map,如其他答案所示。
然后,您的服务层可以使用从application.yml取值并由PortMapper使用的配置对象(例如PortMapperConfiguration),从Port getter有条件地调用PortDTO setter。

@ConfigurationProperties(prefix = "mapper", ignoreUnknownFields = false)
public class PortMapperConfiguration {
    private List<String> include;
    private List<String> exclude;

    // getters/setters
}
@Service
public class PortMapper {
    private PortMapperConfiguration configuration;

    public PortMapper(PortMapperConfiguration configuration) {
        this.configuration = configuration;
    }

    public PortDTO toDto(Port port) {
      PortDTO dto = new PortDTO();

      // Fill DTO based on configuration
      return dto;
    }
}

相关问题