Reputation: 45
I have a following class:
@Data
@NoArgsConstructor
public class FloorPriceData {
Double multiplicationFactor;
Double additionFactor;
Integer heuristicValue;
public static void main(String[] args) {
String a = "{\"multiplicationFactor\" : 3, \"additionFactor\" : 1, \"heuristicValue\" : 3}";
System.out.println(Utils.getMapper().convertValue(a, FloorPriceData.class));
}
}
When I try to convert JSON
{"multiplicationFactor" : 3, "additionFactor" : 1, "heuristicValue" : 3}
to this class instance I get following exception:
Getting Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.medianet.rtb.mowgli.commons.dto.adexchange.FloorPriceData: no String-argument constructor/factory method to deserialize from String value ('{"multiplicationFactor" : 3, "additionFactor" : 1, "heuristicValue" : 3}')
Upvotes: 1
Views: 3319
Reputation: 42184
In this case you should use ObjectMapper.readValue(String json, Class<T> valueType)
:
System.out.println(Utils.getMapper().readValue(a, FloorPriceData.class));
It will generate an output:
FloorPriceData(multiplicationFactor=3.0, additionFactor=1.0, heuristicValue=3)
When you tried deserializing JSON to object with
Utils.getMapper().convertValue(a, FloorPriceData.class)
it failed, because convertValue
firstly serializes given value and then deserializes it again:
This is functionality equivalent to first serializing given value into JSON, then binding JSON data into value of given type, but may be executed without fully serializing into JSON.
In this case it took:
{"multiplicationFactor" : 3, "additionFactor" : 1, "heuristicValue" : 3}
and serialized it to:
"{\"multiplicationFactor\" : 3, \"additionFactor\" : 1, \"heuristicValue\" : 3}"
Upvotes: 1