복붙노트

[SPRING] Spring Rest POST Json RequestBody 지원되지 않는 콘텐츠 유형

SPRING

Spring Rest POST Json RequestBody 지원되지 않는 콘텐츠 유형

게시물 메서드를 사용하여 새 개체를 게시하려고 할 때. 요청 본문에서 콘텐츠 유형을 인식 할 수 없습니다. Spring은 이미 설정되었고 POST는 다른 객체들과 작동 할 수 있지만이 특정 객체는 작동하지 않습니다.

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported

만약 요청 개체를 변경하는 동일한 요청을 시도하십시오. 그것은 작동합니다.

해결법

  1. ==============================

    1.나는 해결책을 찾았다. 같은 이름이지만 다른 유형의 2 명의 세터가 있었기 때문입니다.

    나는 해결책을 찾았다. 같은 이름이지만 다른 유형의 2 명의 세터가 있었기 때문입니다.

    내 클래스는 내 개체를 최대 절전 모드로 만들 때 Integer로 바꾼 id 속성 int를가집니다.

    그러나 분명히, 나는 setters를 제거하는 것을 잊었다. 그리고 나는 가지고 있었다 :

    /**
     * @param id
     *            the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
    
    /**
     * @param id
     *            the id to set
     */
    public void setId(Integer id) {
        this.id = id;
    }
    

    이 세트를 제거하면 작업 요청이 잘 처리됩니다.

    unmarshalling 오류를 던지거나 클래스 오류를 반영하는 데 필요한 정보 예외 HttpMediaTypeNotSupportedException 여기에서 솔기가 정말 이상합니다.

    이 stackoverflow 다른 사람을 도울 수 있기를 바랍니다.

    Spring 서버 콘솔에서 다음과 같은 오류 메시지를 확인할 수 있습니다 :

    그럼 당신은 위에서 언급 한 문제를 다루고 있는지 확인할 수 있습니다.

  2. ==============================

    2.POST에서 전송되지 않는 매개 변수의 속성에 대해 getter 및 setter를 선언 한 경우 (예 : 생성자에서 선언되지 않은 경우 이벤트) (예 :

    POST에서 전송되지 않는 매개 변수의 속성에 대해 getter 및 setter를 선언 한 경우 (예 : 생성자에서 선언되지 않은 경우 이벤트) (예 :

    @RestController
    public class TestController {
    
        @RequestMapping(value = "/test", method = RequestMethod.POST)
        public String test(@RequestBody BeanTest beanTest) {
            return "Hello " + beanTest.getName();
        }
    
    
        public static class BeanTest {
    
            private Long id;
            private String name;
    
            public BeanTest() {
            }
    
            public BeanTest(Long id) {
                this.id = id;
            }
    
            public Long getId() {
                return id;
            }
    
            public void setId(Long id) {
                this.id = id;
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
        }
    }
    

    다음 구조 ({ "id": "1"})로 게시물 요청이 작동하지 않으면 name get 및 set을 삭제해야합니다.

  3. ==============================

    3.정말! 4 시간과 미친 디버깅을 보낸 후 com.fasterxml.jackson.databind.deser.DeserializerCache에서이 매우 이상한 코드를 발견했습니다.

    정말! 4 시간과 미친 디버깅을 보낸 후 com.fasterxml.jackson.databind.deser.DeserializerCache에서이 매우 이상한 코드를 발견했습니다.

    if (deser == null) {
        try {
            deser = _createAndCacheValueDeserializer(ctxt, factory, type);
        } catch (Exception e) {
            return false;
        }
    }
    

    그래, 문제는 두 번 세터였다.

  4. ==============================

    4.Enum과 String을 가진 두 명의 setter가있을 때도 같은 문제가있었습니다. 직렬화 중에 사용할 setter 메서드를 Jackson에게 알려주는 @JsonSetter 주석을 사용해야했습니다. 이게 내 문제를 해결했습니다.

    Enum과 String을 가진 두 명의 setter가있을 때도 같은 문제가있었습니다. 직렬화 중에 사용할 setter 메서드를 Jackson에게 알려주는 @JsonSetter 주석을 사용해야했습니다. 이게 내 문제를 해결했습니다.

  5. ==============================

    5.나는 게시 된 가치를 자신을 비 직렬화함으로써 해결 한 동일한 문제를 만났다.

    나는 게시 된 가치를 자신을 비 직렬화함으로써 해결 한 동일한 문제를 만났다.

    @RequestMapping(value = "/arduinos/commands/{idArduino}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String sendCommandesJson(@PathVariable("idArduino") String idArduino, HttpServletRequest request) throws IOException {
        // getting the posted value
        String body = CharStreams.toString(request.getReader());
        List<ArduinoCommand> commandes = new ObjectMapper().readValue(body, new TypeReference<List<ArduinoCommand>>() {
        });
    

    theses gradle 의존성과 :

      compile('org.springframework.boot:spring-boot-starter-web')
      compile('com.google.guava:guava:16.0.1')
    
  6. ==============================

    6.제 경우 콩에 두 명의 생성자가 있었는데 같은 오류가있었습니다. 나는 그 중 하나를 삭제했고 이제는 문제가 해결되었습니다!

    제 경우 콩에 두 명의 생성자가 있었는데 같은 오류가있었습니다. 나는 그 중 하나를 삭제했고 이제는 문제가 해결되었습니다!

  7. ==============================

    7.그래서 나는 오버로드 된 생성자가있는 빈을 가지고 비슷한 문제가있다. 이 bean에는 선택적 특성도 있습니다.

    그래서 나는 오버로드 된 생성자가있는 빈을 가지고 비슷한 문제가있다. 이 bean에는 선택적 특성도 있습니다.

    문제를 해결하기 위해 오버로드 된 생성자를 제거하고 작동했습니다.

    예:

    public class Bean{
    
    Optional<String> string;
    Optional<AnotherClass> object;
    
    public Bean(Optional<String> str, Optional<AnotherClass> obj){
    string = str;
    object = obj;
    }
    
    ///The problem was below constructor
    
    public Bean(Optional<String> str){
    string = str;
    object = Optional.empty();
    }
    
    
    
    }
    
    }
    
  8. ==============================

    8.lombok을 사용하는 경우 @JsonDeserialize라는 이름을 사용하지 않으면이 오류가 발생할 수 있습니다. 예를 들면 다음과 같습니다.

    lombok을 사용하는 경우 @JsonDeserialize라는 이름을 사용하지 않으면이 오류가 발생할 수 있습니다. 예를 들면 다음과 같습니다.

    @Value
    @Builder(toBuilder = true)
    @JsonDeserialize(builder = SomeClass.SomeOtherClassBuilder.class)
    public class SomeClass {
        ...
        public static class SomeOtherClassBuilder {
            ...
        }
    }
    

    그것은해야한다:

    @Value
    @Builder(toBuilder = true)
    @JsonDeserialize(builder = SomeClass.SomeClassBuilder.class)
    public class SomeClass {
        ...
        public static class SomeClassBuilder {
            ...
        }
    }
    

    클래스 이름을 리팩토링하고 빌더를 잊어 버렸을 때 매우 쉽게 할 수 있습니다 ... 그리고 오류의 원인을 찾는 동안 많은 시간 동안 기쁨을 가졌습니다. 도움이되지 않는 예외 메시지 만 도움이되었습니다.

  9. ==============================

    9.잭슨 의존성을 추가하려고 시도하십시오.

    잭슨 의존성을 추가하려고 시도하십시오.

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.3</version>
        </dependency>
    
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.3</version>
        </dependency>
    
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.3</version>
            <exclusions>
                <exclusion>
                    <artifactId>jackson-annotations</artifactId>
                    <groupId>com.fasterxml.jackson.core</groupId>
                </exclusion>
            </exclusions>
        </dependency>
    
  10. ==============================

    10.낡은 실을 본다. 그러나 누군가가 여전히 고투하는 경우에, 나는 티보가 말했듯이 해결했다.

    낡은 실을 본다. 그러나 누군가가 여전히 고투하는 경우에, 나는 티보가 말했듯이 해결했다.

    두 setter POJO 클래스를 피하기 위해 특정 속성에 대해 두 개의 setter를 사용했습니다. 첫 번째는 정규 setter에 있고 다른 하나는 밑의 constructor에 있습니다.

  11. ==============================

    11.이와 같이 엔티티 클래스 생성자에서 @JsonProperty를 지정하십시오.

    이와 같이 엔티티 클래스 생성자에서 @JsonProperty를 지정하십시오.

    ......
    ......
    ......
    
     @JsonCreator
     public Location(@JsonProperty("sl_no") Long sl_no, 
              @JsonProperty("location")String location,
              @JsonProperty("location_type") String 
              location_type,@JsonProperty("store_sl_no")Long store_sl_no) {
      this.sl_no = sl_no;
      this.location = location;
      this.location_type = location_type;
      this.store_sl_no = store_sl_no;
     } 
    .......
    .......
    .......
    
  12. ==============================

    12.나는 같은 문제가 있었다. 근본 원인이 기본 생성자없이 사용자 지정 deserializer를 사용하고있었습니다.

    나는 같은 문제가 있었다. 근본 원인이 기본 생성자없이 사용자 지정 deserializer를 사용하고있었습니다.

  13. from https://stackoverflow.com/questions/19444855/spring-rest-post-json-requestbody-content-type-not-supported by cc-by-sa and MIT license