Creating Resource with references using spring data rest

后端 未结 2 1582
北海茫月
北海茫月 2020-12-22 07:42

I am using spring data rest, I have following entities exposed via spring data rest

DonationRequest

@Data
@Entity
@Table(name=\"donation_request\",sc         


        
2条回答
  •  有刺的猬
    2020-12-22 08:16

    It can be achieved by using a custom HttpMessageConverter and defining a custom content-type which can be anything other than standard (I used application/mjson):

    MHttpMessageConverter.java

    public class MHttpMessageConverter implements HttpMessageConverter{
        @Override
        public boolean canRead(Class aClass, MediaType mediaType) {
            if (mediaType.getType().equalsIgnoreCase("application")
                    && mediaType.getSubtype().equalsIgnoreCase("mjson"))
                return true;
            else
                return false;
        }
    
        @Override
        public boolean canWrite(Class aClass, MediaType mediaType) {
            return false;
        }
    
        @Override
        public List getSupportedMediaTypes() {
            return new ArrayList<>(Arrays.asList(MediaType.APPLICATION_JSON));
        }
    
        @Override
        public Object read(Class aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
            ObjectMapper mapper = new ObjectMapper();
            Object obj = mapper.readValue(httpInputMessage.getBody(),aClass);
            return obj;
        }
    
        @Override
        public void write(Object o, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
    
        }
    }
    
    
    

    CustomRestConfiguration.java

    @Configuration
    public class CustomRestConfiguration extends RepositoryRestConfigurerAdapter {
    
        @Override
        public void configureHttpMessageConverters(List> messageConverters) {
            messageConverters.add(new MHttpMessageConverter());
        }
    }
    

    提交回复
    热议问题