【问题标题】:How to convert JSON object to a Pair object in JAVA如何在 JAVA 中将 JSON 对象转换为 Pair 对象
【发布时间】:2020-12-18 10:32:11
【问题描述】:

从 API 客户端,我正在发送

{
    "scheduledDateTime": "27-12-2020 08:55:46",
    "subscriptionClosedBy": "30-12-2020 08:55:46",
    "presenter":{"first":"Jone Doe","second":"Senior Tech Lead"}
}

JSON 对象到我的以下 API 端点。

public ResponseEntity<ApiResponse> saveWorkshop(@RequestBody Workshop workshop)

Workshop 类包含如下 Pair 类型属性。

public class Workshop extends PersistObject {
     private LocalDateTime scheduledDateTime;
     private LocalDateTime subscriptionClosedBy;
     private Pair<String, String> presenter;
}

当请求命中端点时抛出异常如下。

原因: com.fasterxml.jackson.databind.exc.InvalidDefinitionException:不能 构造org.springframework.data.util.Pair的实例

我该如何解决这个问题?

【问题讨论】:

    标签: java deserialization jackson-databind


    【解决方案1】:

    我创建了以下自定义反序列化器类

    public final class PairDeserializer extends JsonDeserializer<Pair<String, String>> {
    
        static private ObjectMapper objectMapper = null;
    
        @Override
        public Pair<String, String> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            if (objectMapper == null) {
                objectMapper = new ObjectMapper();
                objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            }
    
            JsonNode treeNode = jsonParser.getCodec().readTree(jsonParser);
            String first = objectMapper.treeToValue(treeNode.get("first"), String.class);
            String second = objectMapper.treeToValue(treeNode.get("second"), String.class);
    
            return Pair.of(first, second);
        }
    }
    

    并将其应用于 Workshop 类,如下所示

     @JsonDeserialize(using = PairDeserializer.class)
        private Pair<String, String> presenter;
    

    然后问题就解决了。

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-29
      • 2012-05-29
      相关资源
      最近更新 更多