Spring Rest POST Json RequestBody内容类型不支持

时间:2021-12-07 18:05:59

When I try to post new object with post method. RequestBody could not recognize contentType. Spring is already configured and POST could work with others objects, but not this specific one.

当我尝试用post方法发布新对象时。RequestBody不能识别contentType。Spring已经配置好,POST可以与其他对象一起工作,但不能与此特定对象一起工作。

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

If I try the same request just changing requestbody object. It works.

如果我尝试相同的请求,只改变requestbody对象。它的工作原理。

10 个解决方案

#1


51  

I found solution. It's was because I had 2 setter with same name but different type.

我发现解决方案。这是因为我有两个相同名字但类型不同的setter。

My class had id property int that I replaced with Integer when à Hibernitify my object.

我的类具有id属性int,在休眠时用整型替换它。

But apparently, I forgot to remove setters and I had :

但是很明显,我忘记移除setter,我有:

/**
 * @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;
}

When I removed this setter, rest resquest work very well.

当我移除这个setter时,rest resquest工作得很好。

Intead to throw unmarshalling error or reflect class error. Exception HttpMediaTypeNotSupportedException seams really strange here.

抛出反编组错误或反映类错误。在这里,异常HttpMediaTypeNotSupportedException异常很奇怪。

I hope this * could be help someone else.

我希望这个*能对其他人有所帮助。

SIDE NOTE

You can check your Spring server console for the following error message:

您可以检查Spring服务器控制台的以下错误消息:

Failed to evaluate Jackson deserialization for type [simple type, class your.package.ClassName]: com.fasterxml.jackson.databind.JsonMappingException: Conflicting setter definitions for property "propertyname"

类型的Jackson反序列化评估失败[simple type,类your.package]。名称:com.fasterxml.jackson.databind。JsonMappingException:属性“propertyname”的冲突setter定义

Then you can be sure you are dealing with the issue mentioned above.

然后你可以确定你正在处理上面提到的问题。

#2


4  

Be aware also if you have declared getters and setters for attributes of the parameter which are not sent in the POST (event if they are not declared in the constructor), for example:

还请注意,如果您已为未在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;
        }
    }
}

A post request with the next structure: {"id":"1"} would not work, you must delete name get and set.

带有下一个结构的post请求:{“id”:“1”}将不起作用,您必须删除name get并设置。

#3


3  

Really! after spending 4 hours and insane debugging I found this very strange code at 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;
    }
}

Ya, the problem was double setter.

是的,问题是双重setter。

#4


1  

I had the same issue when I had two setters one with Enum and one String. I had to use @JsonSetter annotation which tells Jackson what setter method to use during serialization. This solved my issue.

当我有两个setter和Enum和String时,我也有同样的问题。我必须使用@JsonSetter注释,它告诉Jackson在序列化期间使用什么setter方法。这解决了我的问题。

#5


1  

I met the same problem which i solved by deserializing myself the posted value :

我遇到了同样的问题,我通过反序列化我自己发布的值来解决:

@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>>() {
    });

with theses gradle dependencies :

具有这些等级依赖性:

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

#6


1  

In my case I had two Constructors in the bean and I had the same error. I have just deleted one of them and now the issue is fixed!

在我的例子中,我在bean中有两个构造函数,我有相同的错误。我刚刚删除了其中一个,现在问题解决了!

#7


1  

So I had a similar issue where I had a bean with some overloaded constructor. This bean also had Optional properties.

我有一个类似的问题,我有一个带重载构造函数的bean。这个bean也有可选属性。

To resolve that I just removed the overloaded constructors and it worked.

为了解决这个问题,我删除了重载的构造函数,并使其工作。

example:

例子:

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


0  

If you use lobok, you can get that error if you screw up naming of @JsonDeserialize, for example:

如果您使用lobok,如果命名@JsonDeserialize失败,您可以得到这个错误,例如:

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

It should be:

应该是:

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

It is very easy to do that when you do refactoring of class name and forget about Builder... and then you have many hours of joy while you search for reason of error basing on extremely unhelpful exception message.

当您重构类名并忘记构建器时,很容易做到这一点。然后你有很多小时的快乐,当你搜索错误的原因基于非常无用的异常信息。

#9


0  

try to add jackson dependency

尝试添加jackson依赖项

    <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


0  

It looks an old thread, but in case someone still struggles, I have solved as Thibaut said it,

它看起来像一条古老的线,但如果有人还在挣扎,我已经像塞博说的那样解决了,

Avoid having two setter POJO class, I had two-setters for a specific property , The first one was in the regular setter and another one in under constructor after I removed the one in the constructor it worked.

避免有两个setter POJO类,我有一个特定属性的两个setter,第一个在常规setter中,另一个在构造函数中,在我删除了它工作的构造函数中的一个之后。

#1


51  

I found solution. It's was because I had 2 setter with same name but different type.

我发现解决方案。这是因为我有两个相同名字但类型不同的setter。

My class had id property int that I replaced with Integer when à Hibernitify my object.

我的类具有id属性int,在休眠时用整型替换它。

But apparently, I forgot to remove setters and I had :

但是很明显,我忘记移除setter,我有:

/**
 * @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;
}

When I removed this setter, rest resquest work very well.

当我移除这个setter时,rest resquest工作得很好。

Intead to throw unmarshalling error or reflect class error. Exception HttpMediaTypeNotSupportedException seams really strange here.

抛出反编组错误或反映类错误。在这里,异常HttpMediaTypeNotSupportedException异常很奇怪。

I hope this * could be help someone else.

我希望这个*能对其他人有所帮助。

SIDE NOTE

You can check your Spring server console for the following error message:

您可以检查Spring服务器控制台的以下错误消息:

Failed to evaluate Jackson deserialization for type [simple type, class your.package.ClassName]: com.fasterxml.jackson.databind.JsonMappingException: Conflicting setter definitions for property "propertyname"

类型的Jackson反序列化评估失败[simple type,类your.package]。名称:com.fasterxml.jackson.databind。JsonMappingException:属性“propertyname”的冲突setter定义

Then you can be sure you are dealing with the issue mentioned above.

然后你可以确定你正在处理上面提到的问题。

#2


4  

Be aware also if you have declared getters and setters for attributes of the parameter which are not sent in the POST (event if they are not declared in the constructor), for example:

还请注意,如果您已为未在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;
        }
    }
}

A post request with the next structure: {"id":"1"} would not work, you must delete name get and set.

带有下一个结构的post请求:{“id”:“1”}将不起作用,您必须删除name get并设置。

#3


3  

Really! after spending 4 hours and insane debugging I found this very strange code at 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;
    }
}

Ya, the problem was double setter.

是的,问题是双重setter。

#4


1  

I had the same issue when I had two setters one with Enum and one String. I had to use @JsonSetter annotation which tells Jackson what setter method to use during serialization. This solved my issue.

当我有两个setter和Enum和String时,我也有同样的问题。我必须使用@JsonSetter注释,它告诉Jackson在序列化期间使用什么setter方法。这解决了我的问题。

#5


1  

I met the same problem which i solved by deserializing myself the posted value :

我遇到了同样的问题,我通过反序列化我自己发布的值来解决:

@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>>() {
    });

with theses gradle dependencies :

具有这些等级依赖性:

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

#6


1  

In my case I had two Constructors in the bean and I had the same error. I have just deleted one of them and now the issue is fixed!

在我的例子中,我在bean中有两个构造函数,我有相同的错误。我刚刚删除了其中一个,现在问题解决了!

#7


1  

So I had a similar issue where I had a bean with some overloaded constructor. This bean also had Optional properties.

我有一个类似的问题,我有一个带重载构造函数的bean。这个bean也有可选属性。

To resolve that I just removed the overloaded constructors and it worked.

为了解决这个问题,我删除了重载的构造函数,并使其工作。

example:

例子:

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


0  

If you use lobok, you can get that error if you screw up naming of @JsonDeserialize, for example:

如果您使用lobok,如果命名@JsonDeserialize失败,您可以得到这个错误,例如:

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

It should be:

应该是:

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

It is very easy to do that when you do refactoring of class name and forget about Builder... and then you have many hours of joy while you search for reason of error basing on extremely unhelpful exception message.

当您重构类名并忘记构建器时,很容易做到这一点。然后你有很多小时的快乐,当你搜索错误的原因基于非常无用的异常信息。

#9


0  

try to add jackson dependency

尝试添加jackson依赖项

    <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


0  

It looks an old thread, but in case someone still struggles, I have solved as Thibaut said it,

它看起来像一条古老的线,但如果有人还在挣扎,我已经像塞博说的那样解决了,

Avoid having two setter POJO class, I had two-setters for a specific property , The first one was in the regular setter and another one in under constructor after I removed the one in the constructor it worked.

避免有两个setter POJO类,我有一个特定属性的两个setter,第一个在常规setter中,另一个在构造函数中,在我删除了它工作的构造函数中的一个之后。