Json表示布尔的标准形式是true和false,但在项目中也有使用0/1,或者Y/N来表示的。这时候就需要我们将其转换为布尔类型。
package utils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
public class JsonCustomDeserializer extends JsonDeserializer<Boolean> {
@Override
public Boolean deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
JsonToken currentToken = jsonParser.getCurrentToken();
if (currentToken.equals(JsonToken.VALUE_STRING)) {
String text = jsonParser.getText();
if ("X".equals(text)) {
return Boolean.TRUE;
} else if ("".equals(text)) {
return Boolean.FALSE;
}
throw deserializationContext.weirdStringException(text, Boolean.class, "Only X or null values supported.");
} else if (currentToken.equals(JsonToken.VALUE_NULL)) {
return Boolean.FALSE;
}
return deserializationContext.reportBadDefinition(Boolean.class, "Can't parse boolean value: " + jsonParser.getText());
}
}
使用
@TableField("LVORM")
@JsonProperty(value = "LVORM", access = JsonProperty.Access.WRITE_ONLY)
@JsonDeserialize(using = JsonCustomDeserializer.class)
private boolean lvorm;
文章评论