zhaolibin
zhaolibin

Reputation: 11

use jackson serialize, How can I serialize double value null and not return when 0.0

I try to implement custom Jackson serializer, and also I want to handle double value when equals 0.0, writeNull(), and not return.
Here is my serializer code

public class DoubleGTZeroSerializer extends JsonSerializer<Double> {

  private DecimalFormat df = new DecimalFormat("##.##");

  @Override
  public Class<Double> handledType() {
    return Double.class;
  }

  @Override
  public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
      throws IOException, JsonProcessingException {
    if (value != null && value.doubleValue() > 0) {
      gen.writeString(df.format(value));
    } else {
      gen.writeNull();
    }
  }
}

the below is pojo

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Bill implements Serializable {

  private static final long serialVersionUID = -5034123031564773631L;

  @JsonSerialize(using = DoubleToStringSerializer.class)
  private Double orderFee;

  @JsonSerialize(using = DoubleToStringAfterSymbolSerializer.class)
  private Double transFee;

  @JsonSerialize(using = DoubleToStringBeforeSymbolSerializer.class)
  private Double otherFee;

  @JsonSerialize(using = DoubleGTZeroSerializer.class)
  private Double gtZeroFee;
 ...
}

and my request is http://localhost:5509/test?orderFee=10.1&transFee=100.00&otherFee=&gtZeroFee=0 the api result

{
    "status": {
        "desc": "操作成功",
        "code": 0
    },
    "data": [
        {
            "orderFee": "10.1",
            "transFee": "100元",
            "gtZeroFee": null
        }
    ],
    "success": true
}

I don't want to out put the gtZeroFee with null, but the annotation @JsonInclude(JsonInclude.Include.NON_NULL) not works, please help me, thanks all.

Upvotes: 1

Views: 1304

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38665

Instead JsonInclude.Include.NON_NULL you can use JsonInclude.Include.NON_EMPTY and implement isEmpty method:

class DoubleGTZeroSerializer extends JsonSerializer<Double> {

    private DecimalFormat df = new DecimalFormat("##.##");

    @Override
    public Class<Double> handledType() {
        return Double.class;
    }

    @Override
    public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeString(df.format(value));
    }

    @Override
    public boolean isEmpty(SerializerProvider provider, Double value) {
        return value <= 0;
    }
}

and change Bill annotation to:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
class Bill implements Serializable {

Upvotes: 1

Related Questions