bug记录--------JSON parse error:Cannot deserialize value of type `com.test.EnumTest` from String

在查询类型的时候定义了一个枚举EnumTest,这样前端传类型的时候传枚举就可以。

然后在查询的时候报错:

JSON parse error:Cannot deserialize value of type `com.test.EnumTest` from String "ELERTRONIC": value not one of declared Enum instance names: [ELERTRONIC, GENERAL]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `com.test.EnumTest` from String "ELERTRONIC": value not one of declared Enum instance names: [ELERTRONIC, GENERAL] at [Source: (PushbackInputStream); line: 1, column: 148] (through reference chain: com.test.FindParam["type"])

火狐浏览器自动格式化了入参,显示的入参也没有问题。枚举定义如下:

public enum EnumTest {

	/**
	 * 普通
	 **/
	GENERAL(1, "普通"),

	/**
	 * 电子
	 **/
	ELERTRONIC(2, "电子"),;

	/**
	 * value值,存入数据库值
	 */
	private int code;

	/**
	 * 描述
	 */
	private String text;

	EnumTest(int code, String text) {
		this.code = code;
		this.text = text;
	}

	//根据value值获取对应枚举值
	public EnumTest getByCode(Integer code) {
		if (null == code)
			return null;

		for (EnumTest item : values()) {
			if (code == item.getCode()) {
				return item;
			}
		}

		return null;
	}

	/*@JsonCreator
	public static EnumTest jsonCreator(String name) {
		if (StringUtils.isNotBlank(name)) {
			for (EnumTest item : values()) {
				if (item.name().equals(name.trim())) {
					return item;
				}
			}
		}
		return null;
	}*/

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

}

最后发现问题是前端入参传值问题,前端传入的枚举为:"ELERTRONIC   ",也就是枚举后面增加了一个空格(这里为了凸显问题,实际上是多个空格)。

入参问题需要处理,最后将代码中注释解开,处理枚举,解决此问题。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章