JsonMapping异常无法构造实例

JsonMapping exception Cannot construct instance

我有一个关注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));
  }
}

当我尝试转换时 JSON

{"multiplicationFactor" : 3, "additionFactor" : 1, "heuristicValue" : 3}

对于这个 class 实例,我得到以下异常:

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}')

在这种情况下,您应该使用 ObjectMapper.readValue(String json, Class<T> valueType):

System.out.println(Utils.getMapper().readValue(a, FloorPriceData.class));

它将生成一个输出:

FloorPriceData(multiplicationFactor=3.0, additionFactor=1.0, heuristicValue=3)

当您尝试反序列化 JSON 以反对

Utils.getMapper().convertValue(a, FloorPriceData.class)

失败,因为convertValue首先序列化给定值,然后再次反序列化:

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.

在这种情况下,它花费了:

{"multiplicationFactor" : 3, "additionFactor" : 1, "heuristicValue" : 3}

并将其序列化为:

"{\"multiplicationFactor\" : 3, \"additionFactor\" : 1, \"heuristicValue\" : 3}"