无法读取JSON

时间:2015-05-05 19:09:35

标签: json spring spring-mvc jackson

我的控制器如下。 RelationTypeTable类中的字段。我得到以下异常。有什么想法吗?

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not construct instance of com.mycompany.myapp.core.domain.RelationType from String value 'unionetomany': value not one of declared Enum instance names: [unionetoone, unionetomany]
 at [Source: org.apache.catalina.connector.CoyoteInputStream@7b3e44cb; line: 1, column: 435] (through reference chain: com.mycompany.myapp.core.domain.Table["relations"]->com.mycompany.myapp.core.domain.Relation["relationtype"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of com.mycompany.myapp.core.domain.RelationType from String value 'unionetomany': value not one of declared Enum instance names: [unionetoone, unionetomany, unimanytoone, unimanytomany, bionetoone, bionetomany, bimanytoone, bimanytomany]
 at [Source: org.apache.catalina.connector.CoyoteInputStream@7b3e44cb; line: 1, column: 435] (through reference chain: com.mycompany.myapp.core.domain.Table["relations"]->com.mycompany.myapp.core.domain.Relation["relationtype"])
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:228)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.read(MappingJackson2HttpMessageConverter.java:220)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:183)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:98)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:79)

@RequestMapping(method = RequestMethod.POST)
    public void validateSchema(@RequestBody Table[] tables, HttpServletRequest request) {
    ......
}

public enum RelationType {
  UNI_ONE_TO_ONE("unionetoone"),
  UNI_ONE_TO_MANY("unionetomany");

  private final String text;

  private RelationType(final String text) {
      this.text = text;
  }

  @Override
  public String toString() {
      return text;
  }
}

1 个答案:

答案 0 :(得分:2)

默认情况下Enum s name用于序列化,而不是toString()返回。因此,虽然错误消息令人困惑(它应列出预期的实际值),但问题是它需要UNI_ONE_TO_MANY

如果要使用toString()返回的值,您应该能够向@JsonValue方法添加注释toString(),并且应该指示该值应该用于序列化。< / p>

另一种方法是启用DeserializationFeature.READ_ENUMS_USING_TO_STRING,这将改变全局行为。