Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@JsonSerialize / @JsonDeserialize not invoked with Spring MVC

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?

like image 751
Marty Pitt Avatar asked Jan 26 '12 21:01

Marty Pitt


2 Answers

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).

like image 104
waxwing Avatar answered Nov 06 '22 23:11

waxwing


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;
}
like image 33
Ondřej Z Avatar answered Nov 06 '22 22:11

Ondřej Z