我也找不到布尔的类似功能。所以,我建议为布尔字段编写新的序列化器和反序列化器。
看我的例子:
public class JacksonProgram {
public static void main(String[] args) throws IOException {
Foo foo = new Foo();
foo.setB(true);
foo.setS("Test");
foo.setI(39);
ObjectMapper objectMapper = new ObjectMapper();
JsonFactory jsonFactory = new JsonFactory();
StringWriter stringWriter = new StringWriter();
JsonGenerator jsonGenerator = jsonFactory.createGenerator(stringWriter);
jsonGenerator.enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
objectMapper.writeValue(jsonGenerator, foo);
System.out.println(stringWriter);
JsonParser jsonParser = jsonFactory.createJsonParser(stringWriter.toString());
Foo value = objectMapper.readValue(jsonParser, Foo.class);
System.out.println(value);
}
}
class BooleanSerializer extends JsonSerializer<Boolean> {
@Override
public void serialize(Boolean value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeString(value.toString());
}
}
class BooleanDeserializer extends JsonDeserializer<Boolean> {
public Boolean deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
return Boolean.valueOf(jsonParser.getValueAsString());
}
}
class Foo {
@JsonSerialize(using = BooleanSerializer.class)
@JsonDeserialize(using = BooleanDeserializer.class)
private boolean b;
private String s;
private int i;
public boolean isB() {
return b;
}
public void setB(boolean b) {
this.b = b;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
@Override
public String toString() {
return "Foo [b=" + b + ", s=" + s + ", i=" + i + "]";
}
}
输出:
{"b":"true","s":"Test","i":"39"}
Foo [b=true, s=Test, i=39]
编辑
我认为,您应该将SimpleModule
配置添加到ObjectMapper
:
SimpleModule simpleModule = new SimpleModule("BooleanModule");
simpleModule.addSerializer(Boolean.class, new BooleanSerializer());
simpleModule.addDeserializer(Boolean.class, new BooleanDeserializer());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(simpleModule);
现在,您应该能够序列化 boolean/Object List-s 和 Map-s。