正如保罗佩德罗索的答案所提及和引用的那样,你需要自己定制JsonSerializer
和自定义JsonDeserializer
.创建后,您需要在属性中添加@JsonSerialize
和@JsonDeserialize
注释; 指定要用于每个的类.
我在下面提供了一个小的(希望直截了当的)示例.串行器和解串器实现都不是非常强大,但这应该可以帮助您入门.
public static class SimplePojo { @JsonProperty @JsonSerialize(using=NumericBooleanSerializer.class) @JsonDeserialize(using=NumericBooleanDeserializer.class) Boolean bool; } public static class NumericBooleanSerializer extends JsonSerializer{ @Override public void serialize(Boolean bool, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException { generator.writeString(bool ? "1" : "0"); } } public static class NumericBooleanDeserializer extends JsonDeserializer { @Override public Boolean deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { return !"0".equals(parser.getText()); } } @Test public void readAndWrite() throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); // read it SimplePojo sp = mapper.readValue("{\"bool\":\"0\"}", SimplePojo.class); assertThat(sp.bool, is(false)); // write it StringWriter writer = new StringWriter(); mapper.writeValue(writer, sp); assertThat(writer.toString(), is("{\"bool\":\"0\"}")); }