JavaTuples API - can not deserialize as they do NOT have no args constructor

77 views Asked by At

I am using javatuples as I have to return multiple arguments from few of my methods calls.

Everything seem good until I tried to deserialize a jsonString in to a Triplet. Seems the tuples classes(Triplet etc) don't have a no-args constructor, so jackson is not able to deserialize.

My code is roughly as below -

String json = """{"size":3,"value0":["dataPoint1", "dataPoint2"],"value1":["dataPoint3"],"value2":["dataPoint2", "dataPoint3"]}""";   
Triplet<List<String>, List<String>, List<String>> serviceResponse = objectMapper.readValue(json, new TypeReference<>(){});

And the exception I am getting is -

Cannot construct instance of org.javatuples.Triplet (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

DO I HAVE ANY OTHER WORK AROUNDS? My actual data i very huge so deserilzation approach is required for my case. Are there any jackson configuration etc that can fix this issue.

I am thinking a Custom JsonDeserializer might help. But other simple solutions are welcome too.

2

There are 2 answers

0
PeterMmm On

The JSON Object seems to map to

class T {
 int size;
 List<String> value1;
 List<String> value2;
 List<String> value3;
}

Why not deserialize into this object ?

0
Diego Borba On

From what I have researched, you can't configure this in Jackson. In my opinion, your best solution would be to use a Custom JsonDeserializer, as you already know.

Based on your example, I do it this way:

public class TripletDeserializer extends JsonDeserializer<Triplet<List<String>, List<String>, List<String>>> {
    @Override
    public Triplet<List<String>, List<String>, List<String>> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        return new Triplet<>(getNodeList(node.get("value0")), getNodeList(node.get("value1")), getNodeList(node.get("value2")));
    }

    private List<String> getNodeList(JsonNode valueNode) {
        List<String> value = new ArrayList<>();
        if (valueNode != null && valueNode.isArray()) {
            for (JsonNode element : valueNode) {
                value.add(element.asText());
            }
        }
        return value;
    }
}