Java 不支持 Spring Rest POST Json RequestBody 内容类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19444855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Rest POST Json RequestBody Content type not supported
提问by Thibaut
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 对象。有用。
回答by Thibaut
I found solution. It's was because I had 2 setter with same name but different type.
我找到了解决方案。这是因为我有 2 个名称相同但类型不同的二传手。
My class had idproperty int that I replaced with Integer when à Hibernitify my object.
我的班级有id属性 int ,当我对我的对象进行休眠时,我将其替换为 Integer 。
But apparently, I forgot to remove setters and I had :
但显然,我忘了删除二传手,我有:
/**
* @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.
Intead 抛出解组错误或反映类错误。异常 HttpMediaTypeNotSupportedException 在这里接缝真的很奇怪。
I hope this stackoverflow could be help someone else.
我希望这个 stackoverflow 可以帮助别人。
SIDE NOTE
边注
You can check your Spring serverconsole for the following error message:
您可以检查Spring 服务器控制台是否有以下错误消息:
Failed to evaluate Hymanson deserialization for type [simple type, class your.package.ClassName]: com.fasterxml.Hymanson.databind.JsonMappingException: Conflicting setter definitions for property "propertyname"
无法评估类型 [simple type, class your.package.ClassName] 的 Hymanson 反序列化:com.fasterxml.Hymanson.databind.JsonMappingException:属性“propertyname”的 setter 定义冲突
Then you can be sure you are dealing with the issue mentioned above.
那么您就可以确定您正在处理上述问题。
回答by Reza Shahbazi
Really! after spending 4 hours and insane debugging I found this very strange code at com.fasterxml.Hymanson.databind.deser.DeserializerCache
真的!在花了 4 个小时和疯狂的调试之后,我在 com.fasterxml.Hymanson.databind.deser.DeserializerCache 发现了这个非常奇怪的代码
if (deser == null) {
try {
deser = _createAndCacheValueDeserializer(ctxt, factory, type);
} catch (Exception e) {
return false;
}
}
Ya, the problem was double setter.
是的,问题是双重二传手。
回答by alvgarvilla
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 和 set。
回答by Kartheek Mannepalli
I had the same issue when I had two setters one with Enum and one String. I had to use @JsonSetter annotation which tells Hymanson what setter method to use during serialization. This solved my issue.
当我有两个 setter 时,我遇到了同样的问题,一个是 Enum,一个是 String。我不得不使用 @JsonSetter 注释,它告诉Hyman逊在序列化期间使用什么 setter 方法。这解决了我的问题。
回答by Serge Tahé
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 :
具有这些 gradle 依赖项:
compile('org.springframework.boot:spring-boot-starter-web')
compile('com.google.guava:guava:16.0.1')
回答by osoitza
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 中有两个构造函数,并且出现了同样的错误。我刚刚删除了其中之一,现在问题已解决!
回答by user_CC
So I had a similar issue where I had a bean with some overloaded constructor. This bean also had Optional properties.
所以我有一个类似的问题,我有一个带有一些重载构造函数的 bean。这个 bean 也有 Optional 属性。
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();
}
}
}
回答by Mader Levap
If you use lombok, you can get that error if you screw up naming of @JsonDeserialize, for example:
如果你使用 lombok,如果你搞砸了 @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, while having as help only extremely unhelpful exception message.
当您重构类名并忘记 Builder 时,很容易做到这一点......然后您在搜索错误原因时有很多小时的快乐,同时只有非常无用的异常消息作为帮助。
回答by Aborn Jiang
try to add Hymanson dependency
尝试添加Hyman逊依赖
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-core</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-annotations</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-databind</artifactId>
<version>2.9.3</version>
<exclusions>
<exclusion>
<artifactId>Hymanson-annotations</artifactId>
<groupId>com.fasterxml.Hymanson.core</groupId>
</exclusion>
</exclusions>
</dependency>
回答by Dapper Dan
It looks an old thread, but in case someone still struggles, I have solved as Thibaut said it,
它看起来是一个旧线程,但如果有人仍然在挣扎,我已经解决了 Thibaut 所说的,
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 中,另一个在构造函数下,在我删除了它工作的构造函数中的一个之后。