Dfr Dfr - 6 months ago 28
JSON Question

Java "Jackson" JsonMappingException: Can not deserialize instance of float out of FIELD_NAME token

with this class:

public class Products implements Serializable {
private BigDecimal productId;
private float priority;

public float getPriority() {
return priority;
}

public void setPriority(float priority) {
this.priority = priority;
}
}


When doing deserialization of such JSON data:

{"productId":47552,"priority":78}


Got this error:

org.codehaus.jackson.map.JsonMappingException:
Can not deserialize instance of float out of FIELD_NAME token
at [Source: org.apache.catalina.connector.CoyoteInputStream@103cf49; line: 1, \
column: 290] (through reference chain: entity.Products["priority"])


But for this data (quotes around priority value)

{"productId":47552,"priority":"78"}


works well, so it seems that jackson (1.9.9) does not respect numeric values ? I suspect something is wrong here.

Answer

You are declaring the field priority as a float type and you try to deserialize the Json which contains int value. Jackson try to call a setter function which accepts a integer value. So we need to add one setter like this.

public void setPriority(int priority){
    this.priority = Float.valueOf(priority);
}