简体   繁体   中英

How to convert JSON object to a Pair object in JAVA

From the API client, I am sending

{
    "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.

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

Workshop class contains a Pair type attribute as follows.

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

How can I overcome this issue?

I created the following custom deserializer 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

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

Then the issue was solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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