I have a Spring 3.1 MVC project, and I'm having trouble deserializing a request sent to the following controller method:
@RequestMapping(value="/deposit",method=RequestMethod.POST)
public void deposit(@RequestBody DepositRequest request)
{
}
The request object which contains a Joda Money value, which I've registered a custom serializer/deserializer for:
public class DepositRequest {
private Money amount;
@JsonDeserialize(using=JodaMoneyDeserializer.class)
@JsonSerialize(using=JodaMoneySerializer.class)
public Money getAmount() {
return amount;
}
public void setAmount(Money amount) {
this.amount = amount;
}
}
And the deserializer:
public class JodaMoneyDeserializer extends JsonDeserializer<Money> {
@Override
public Money deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
String text = parser.getText();
return Money.parse(text);
}
}
However, this deserializer is never invoked. When I send the following JSON, I get a 400 - Bad Request
response, which I assume indicates that the mapper wasn't found.
{
"amount" : "30AUD"
}
Do I need to tell Spring about this mapper somehow, or is the annotation enough? What other steps should I be taking to get the deserialization to work?
According to the Javadoc of JsonDeserialize
you should use that annotation on the setter, not the getter (while JsonSerialize
should indeed be on the getter).
You could also attach your deserializer/serializer to amount field:
@JsonDeserialize(using=JodaMoneyDeserializer.class)
@JsonSerialize(using=JodaMoneySerializer.class)
private Money amount;
public Money getAmount() {
return amount;
}
public void setAmount(Money amount) {
this.amount = amount;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With