Spring Boot - 不同的模型表示/多个API

时间:2016-12-13 19:32:54

标签: java json spring rest api

我的后端必须提供两种不同的API - 分别对相同模型的不同访问,相同的实现和对数据库的相同映射。模型作为JSON发送,后端以相同的方式使用它们。

但每个API都需要不同的JSON表示。 F.E.我想以不同的方式命名一些字段(w / @JsonProperty f.e.)或想要省略一些字段。

如上所述,控制器应该以与制作它们相同的方式使用它们。

由于只有表示不同:是否有一种简单且符合DRY的方法来实现这一目标?

示例:

调用

min

应该返回

ProductsController.java

    sym/products/1

并致电

{
  "id": 1,
  "title": "stuff",
  "label": "junk"
}

应该返回

ProductsController.java

    frontend/products/1

非常感谢!

2 个答案:

答案 0 :(得分:0)

单独的DTO可能是最佳解决方案。

备用(假设您使用Jackson)是让一个DTO具有所有不同的字段,然后使用MixIns来控制DTO的序列化方式。

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

    public static void main(String[] args) throws Exception  {

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.addMixIn(SomeDTOWithLabel.class, IgnoreLabelMixin.class);

        SomeDTOWithLabel dto = new SomeDTOWithLabel();
        dto.setLabel("Hello World");
        dto.setOtherProperty("Other property");
        String json = objectMapper.writeValueAsString(dto);
        System.out.println("json = " + json);
    }

    public static class SomeDTOWithLabel {
        private String label;
        private String otherProperty;

        public String getOtherProperty() {
            return otherProperty;
        }

        public void setOtherProperty(String otherProperty) {
            this.otherProperty = otherProperty;
        }

        public String getLabel() {
            return label;
        }
        public void setLabel(String label) {
            this.label = label;
        }
    }

    public abstract class IgnoreLabelMixin {
        @JsonIgnore
        public abstract String getLabel();

    }
}

例如,我们的DTO具有旧客户可能仍然依赖的弃用属性,但我们不想将它们发送给新客户端,因此我们使用MixIns来压制它们。

答案 1 :(得分:0)

如果这只是根据您调用的路径返回轻量级有效负载的情况,则可以配置json序列化程序(ObjectMapper)以省略空字段。然后在您的服务中,只选择并填充您希望返回的字段子集。

    objectMapper.setSerializationInclusion(Include.NON_NULL); // omits null fields

但是,如果您希望返回不同的命名字段,请使用其他API模型。