Spring Download - Various Model Views / Multiple APIs

my backend should offer two different APIs - different access to the same models , respectively, to the same implementation and to the same database comparisons. Models are sent as JSON, and they are also used by the backend in the same way.

But each API requires different JSON representations. FE I would like to name several fields differently (w / @ JsonProperty fe) or want to omit some.

As already mentioned, they must be consumed by the controllers in the same way as they are created.

Since only the view is different: is there a simple and harsh way to accomplish this?

Example:

Call

ProductsController.java

    sym/products/1

must return

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

and challenge

ProductsController.java

    frontend/products/1

must return

{
  "id": 1,
  "label": "junk",
  "description": "oxmox",
  "even-more": "text"
}

Thank you so much!

Tim

+1
2

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 .

0

, , json (ObjectMapper), . , .

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

, , API.

0

Source: https://habr.com/ru/post/1665792/


All Articles