简体   繁体   English

如何在 ZC71E8D17D41C21DE0D260881D6966 中将 JSON object 转换为一对 object

[英]How to convert JSON object to a Pair object in JAVA

From the API client, I am sending从 API 客户端,我发送

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

JSON object to my following API endpoint. JSON object 到我的以下 API 端点。

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

Workshop class contains a Pair type attribute as follows. Workshop class 包含一个 Pair 类型属性,如下所示。

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

When the request hits the endpoint exception is thrown as follows.当请求到达端点时,抛出如下异常。

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of org.springframework.data.util.Pair引起:com.fasterxml.jackson.databind.exc.InvalidDefinitionException:无法构造org.springframework.data.util.Pair的实例

How can I overcome this issue?我该如何克服这个问题?

I created the following custom deserializer class我创建了以下自定义解串器 class

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

and applied it to the Workshop class as follows并将其应用于车间 class 如下

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

Then the issue was solved.然后问题就解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM