当前位置: 首页 > 知识库问答 >
问题:

Jackson反序列化错误:没有从字符串值反序列化的字符串参数构造函数/工厂方法

徐飞尘
2023-03-14

我正在尝试反序列化以下JSON

{
  "deliverLumpSum": 0.0,
  "faxQId": "{\"type\":\"TAKEAWAY\",\"data\":{\"orderId\":\"AWSWD-AWSAW\",\"orderKey\":\"DERS34S32SD\"}}"
}

在以下自定义反序列化程序的帮助下

public class OrderIdDeserializer extends JsonDeserializer<OrderId> {

  @Override
  public OrderId deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
      OrderId orderId = jsonParser.readValueAs(OrderId.class);
      return orderId;
  }
}

进入以下对象结构

@Data
public class AddInfo {

  protected double deliverLumpSum;
  
  @JsonDeserialize( using = OrderIdDeserializer.class)
  public OrderId orderId;

}

@Data
public class OrderId {

  private String type;
  private TakeawayData data;

}

@Data
public class TakeawayData {

  private String orderId;
  private String orderKey;

}

我得到以下错误

通用域名格式。fasterxml。杰克逊。数据绑定。exc.MismatchedInputException:无法构造OrderId的实例(尽管至少存在一个创建者):没有从字符串值反序列化的字符串参数构造函数/工厂方法({“type”:“TAKEAWAY”,“data”:{“OrderId”:“AWSWD-AWSAW”,“orderKey”:“DERS34S32SD”}}})

我做错了什么?我该如何解决这个问题?

共有1个答案

凤安然
2023-03-14

首先,您的JSON示例("faxQId":)与您的Java类AddInfo不匹配:

@JsonDeserialize( using = OrderIdDeserializer.class)
public OrderId orderId;

我猜这只是一个复制粘贴错误,你真的是说

@JsonDeserialize( using = OrderIdDeserializer.class)
public OrderId faxQId;

现在来看真正的问题。在“faxQId”之后的JSON内容:有一个包含JSON代码的JSON字符串(带有正确转义的引号)

"faxQId": "{\"type\":\"TAKEAWAY\",\"data\":{\"orderId\":\"AWSWD-AWSAW\",\"orderKey\":\"DERS34S32SD\"}}"

而不仅仅是一个普通的JSON对象,比如

"faxQId": {"type":"TAKEAWAY","data":{"orderId":"AWSWD-AWSAW","orderKey":"DERS34S32SD"}}"

因此,在反序列化器中,您需要额外的步骤将此String反序列化为Java对象。

public class OrderIdDeserializer extends JsonDeserializer<OrderId> {

  @Override
  public OrderId deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {

    // Get the JSON text (with the \ already decoded):
    // {"type":"TAKEAWAY","data":{"orderId":"AWSWD-AWSAW","orderKey":"DERS34S32SD"}}
    String s = jsonParser.getValueAsString();
      
    // We need a second parser for deserializing the JSON text
    JsonParser jsonParser2 = jsonParser.getCodec().getFactory().createParser(s);

    // Convert the JSON text into an object
    return jsonParser2.readValueAs(OrderId.class);
  }
}
 类似资料: