【发布时间】:2015-09-28 14:08:40
【问题描述】:
我目前面临将 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: Content type 'application/json;charset=UTF-8' not supported
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 类的方式有问题,导致它无法反序列化。有哪位有线索可以帮帮我吗?
【问题讨论】:
-
你的问题出现在反序列化之前;从您的
@RequestMapping中删除headers并将内容类型设置为application/json -
我设法修复了它。我的帖子大多无关紧要。我查看了stackoverflow.com/a/19444874/2364671 虽然 Property 没有任何属性的设置器,但它有一个名为 SetUserWeights 的方法以某种方式破坏了一切,我重命名了该方法并解决了问题。我不明白为什么这种方法会破坏我的反序列化。感谢您的宝贵时间。
标签: java json spring deserialization