How to convert JSON string or eml file to Message object in Gmail API with Java?

Viewed 364

I am trying to convert a JSON object to a Message class. I tried looking for any internal google libraries that did it but didn't find anything.

In case of default ObjectMapper from Jackson library, it causes type casting issues as Message class has BigInteger, Long and Integer fields. This is the custom deserializer I defined-

@Override
    public Message deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectMapper om=new ObjectMapper();
        JsonNode node=p.getCodec().readTree(p);
        String id= node.get("id").asText();
        BigInteger historyId= node.get("historyId").bigIntegerValue();
        long internalDate= node.get("internalDate").longValue();
        List<String> labelIds= Arrays.asList(node.get("labelIds").asText().split(","));
        MessagePart payload= om.treeToValue(node.get("payload"), MessagePart.class);
        int sizeEstimate= node.get("sizeEstimate").asInt();
        String snippet= node.get("snippet").asText();
        Message result=new Message();
        result.setPayload(payload);
        result.setId(id);
        result.setHistoryId(historyId);
        result.setInternalDate(internalDate);
        result.setLabelIds(labelIds);
        result.setSizeEstimate(sizeEstimate);
        result.setSnippet(snippet);
        return result;
    }

Here mData is the json as String.

SimpleModule module=new SimpleModule();
        module.addDeserializer(Message.class, new JsonMessageDeserialzer());
        objectMapper.registerModule(module);
        Message message2= objectMapper.readValue(mData, Message.class);

which gives this error-

fasterxml.jackson.databind.JsonMappingException: Can not set com.google.api.services.gmail.model.MessagePartBody field com.google.api.services.gmail.model.MessagePart.body to java.util.LinkedHashMap (through reference chain: com.google.api.services.gmail.model.MessagePart["body"])

The only approach I see is to create another custom deserializer for MessagePart but it seems really complicated to get it right because of all the nested objects. Any help would be appreciated. Thanks!

1 Answers

It seemed really complicated to do it this way. Instead using Gson default parser, you can recreate the MessagePart and MessagePartBody. For the rest you will have to do it manually.

Related