Skip to content
Advertisement

Serializing a double property as string

Which @JsonXyz annotation do I have to use when I have a bean to be jsonified but serializing a double proeprty as string.

An example: I have a bean:

public MyBean {
    private double myDouble;
    //getter and setter
}

And I wan tto have a JSON like:

{'myDouble':'100.0'}

instead of:

{'myDouble':100.0}

So, the value 100.0 shall be in quotes.

Advertisement

Answer

If you are using Jackson you can use @JsonSerialize and ToStringSerializer :

public MyBean {
    @JsonSerialize(using = ToStringSerializer.class)
    private double myDouble;
    //getter and setter
    //constructors
}

The code to test it (Jackson version 2.9.8) :

MyBean myBean = new MyBean(20.3);

ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(myBean);

System.out.println(json);

The output is :

{"myDouble":"20.3"}
Advertisement