How can I Serialize/De-serialize a Boolean Value from FasterXML\Jackson as an Int?

后端 未结 2 604
小鲜肉
小鲜肉 2021-01-01 14:41

I\'m writing a JSON Client for a Server that returns Boolean values as \"0\" and \"1\". When I try to run my JSON Client I currently get the following Exception:

2条回答
  •  天涯浪人
    2021-01-01 15:02

    As Paulo Pedroso's answer mentioned and referenced, you will need to roll your own custom JsonSerializer and JsonDeserializer. Once created, you will need to add the @JsonSerialize and @JsonDeserialize annotations to your property; specifying the class to use for each.

    I have provided a small (hopefully straightforward) example below. Neither the serializer nor deserializer implementations are super robust but this should get you started.

    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\"}"));
    }
    

提交回复
热议问题