Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java to Jackson JSON serialization: Money fields

Currently, I'm using Jackson to send out JSON results from my Spring-based web application.

The problem I'm having is trying to get all money fields to output with 2 decimal places. I wasn't able to solve this problem using setScale(2), as numbers like 25.50 are truncated to 25.5 etc

Has anyone else dealt with this problem? I was thinking about making a Money class with a custom Jackson serializer... can you make a custom serializer for a field variable? You probably can... But even still, how could I get my customer serializer to add the number as a number with 2 decimal places?

like image 963
ControlAltDel Avatar asked Jul 03 '12 21:07

ControlAltDel


People also ask

How do you serialize an object to JSON Jackson in Java?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.

Does Jackson use Java serialization?

This short tutorial shows how the Jackson library can be used to serialize Java object to XML and deserialize them back to objects.

Does Jackson serialize null fields?

With its default settings, Jackson serializes null-valued public fields. In other words, resulting JSON will include null fields. Here, the name field which is null is in the resulting JSON string.


2 Answers

You can use a custom serializer at your money field. Here's an example with a MoneyBean. The field amount gets annotated with @JsonSerialize(using=...).

public class MoneyBean {     //...      @JsonProperty("amountOfMoney")     @JsonSerialize(using = MoneySerializer.class)     private BigDecimal amount;      //getters/setters... }  public class MoneySerializer extends JsonSerializer<BigDecimal> {     @Override     public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException,             JsonProcessingException {         // put your desired money style here         jgen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());     } } 

That's it. A BigDecimal is now printed in the right way. I used a simple testcase to show it:

@Test public void jsonSerializationTest() throws Exception {      MoneyBean m = new MoneyBean();      m.setAmount(new BigDecimal("20.3"));       ObjectMapper mapper = new ObjectMapper();      assertEquals("{\"amountOfMoney\":\"20.30\"}", mapper.writeValueAsString(m)); } 
like image 198
Steve Avatar answered Oct 06 '22 23:10

Steve


You can use @JsonFormat annotation with shape as STRING on your BigDecimal variables. Refer below:

 import com.fasterxml.jackson.annotation.JsonFormat;    class YourObjectClass {        @JsonFormat(shape=JsonFormat.Shape.STRING)       private BigDecimal yourVariable;   } 
like image 20
Sahil Chhabra Avatar answered Oct 07 '22 00:10

Sahil Chhabra