2

I have a class to which a deserialize a server response:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Card {

double amount;

String cardType;
String cardNumber
... many more properties
}

API is not very consistent, so for my request in question I get a string "$74.50" which fails obviously to parse to double as is. I can't modify the class as it will probably fail something elsewhere where it's actual double.

Can I make condition for jackson to take the string literally without modifying the class? I think I can do so with custom deserializer on ObjectMapper like here, but not sure how to pull it off exactly.

ephemeris
  • 755
  • 9
  • 21

1 Answers1

1

Create additional setter for amount:

@JsonSetter("amount")
public void setAmount(String sAmount) {
    // parse "$74.50" to 74.50 here
    this.amount = parsedAmount;
}

It will be called for field like {"amount": "$74.50"} and correct set amount in your class.

Bor Laze
  • 2,458
  • 12
  • 20