2015-05-05 109 views
1

我有我的控制器,如下所示。 RelationTypeTable類中的字段。我有以下例外。有任何想法嗎?無法讀取JSON

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: [email protected]; 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: [email protected]; 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; 
    } 
} 

回答

2

默認情況下Enum小號name用於序列化,不能什麼toString()回報。所以,雖然錯誤信息令人困惑(它應該列出預期的實際值),但問題在於預期爲UNI_ONE_TO_MANY

如果您想使用toString()返回的值,您應該可以將註釋@JsonValue添加到toString()方法,並且應該指示該值應該用於序列化。

另一種方法是啓用DeserializationFeature.READ_ENUMS_USING_TO_STRING,這將改變全局行爲。