我目前面临将json反序列化为多态类型的问题。
这是我的控制器,它接收一个RecommendedVirtualEditionParam。
@RequestMapping(
value = "/sortedEdition",
method = RequestMethod.POST,
headers = { "Content-type=application/json;charset=UTF-8"
})
public String getSortedRecommendedVirtualEdition(
Model model,
@RequestBody RecommendVirtualEditionParam params) {
//Do Stuff
}
RecommendedVirtualEditionParam是一个容器:
public class RecommendVirtualEditionParam {
private final String acronym;
private final String id;
private final Collection<Property> properties;
public RecommendVirtualEditionParam(
@JsonProperty("acronym") String acronym,
@JsonProperty("id") String id,
@JsonProperty("properties") Collection<Property> properties) {
this.acronym = acronym;
this.id = id;
this.properties = properties;
}
//Getters
}
属性是一种多态类型,我相信它是给我问题的那个。
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = SpecificTaxonomyProperty.class, name = "specific-taxonomy")
})
public abstract class Property {
public Property() {
}
//Other methods
}
子类型:
public class SpecificTaxonomyProperty extends Property {
private final String acronym;
private final String taxonomy;
public SpecificTaxonomyProperty(
@JsonProperty("acronym") String acronym,
@JsonProperty("taxonomy") String taxonomy) {
this.acronym = acronym;
this.taxonomy = taxonomy;
}
根据请求发送json:
{
acronym: "afs"
id: "167503724747"
properties: [
{
type: "specific-taxonomy",
acronym: "afs",
taxonomy: "afs"
}
]
}
当我像这样运行它时,我得到一个org.springframework.web.HttpMediaTypeNotSupportedException:内容类型&#39; application / json; charset = UTF-8&#39;不支持
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:149) ~[spring-webmvc-3.2.2.RELEASE.jar:3.2.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:180) ~[spring-webmvc-3.2.2.RELEASE.jar:3.2.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:95) ~[spring-webmvc-3.2.2.RELEASE.jar:3.2.2.RELEASE]
我认为设置Property类使其无法反序列化的方式有问题。任何有线索并给我一个手?
答案 0 :(得分:0)
我设法解决了我的问题。
在发帖之前,我已经环顾四周,很多答案都指向了我想要反序列化同一属性的多个setter的类。我没有太注意它,因为我的属性是最终的,我没有为他们设置任何人。
https://stackoverflow.com/a/19444874/2364671
但我有一个名为setUserWeight(RecommendedWeights权重)的方法,它没有设置属性的任何属性,但在重命名后,我的问题得到了解决。
我不会安静地理解这种奇怪行为的原因,并且会对此有所了解。