1

I am not a Java programmer but keen to know how to achieve a feature which would ignore one or more invalid fields while de-serializing. In my case, the byte[] is send by a legacy system and hence no control over data correction (on encoding side or to send default in case of missing). This means, I need to anticipate invalid data/missing data within the byte[].

Following code serialize payloads but throws exception upon receiving invalid (wrong encoding, null etc).

   public class LDeserializer<T> implements Deserializer<T> {

    private final ObjectMapper objectMapper;
    private final Class<T> myType;

    public LDeserializer(final ObjectMapper objectMapper, final Class<T> myType) {
        this.objectMapper = objectMapper;
        this.myType = myType;
      }

    public LDeserializer(final Class<T> myType) {
        this(new ObjectMapper(), myType);
    }

    @Override
    public T deserialize(final String sometext, final byte[] bytes) {
        if (bytes == null) {
            return null;
        }

        try {
            return objectMapper.readValue(bytes, myType);
        } catch (final IOException e) {
            throw new SerializationException(e);
        }
    }
}

Question: In my case, I can safely ignore invalid values while serialization. However, I am not sure how to instruct my serializer to ignore invalid fields (irrespective of its type). So that the serializer would emit object even thou the constructed object is not complete.

Note: ObjectMapper is the type I am using here to support serialization. However, I am free to use any helper types that can be used instead ObjectMapper. The only concern here is how to ignore invalid fields (irrespective of its type).

Please advise

S.N
  • 4,910
  • 5
  • 31
  • 51
  • What are **invalid fields** in your case? If the fields are just not known in the class [this answer](https://stackoverflow.com/a/12730655/8178842) might be a solution. – Tobias Sep 12 '20 at 11:06
  • @Tobias, For eg: The payload has string data. But this string data is not encoded correctly while storing. This means, when I receive such poorly formatted string, my deserializer throws exception while reporting ''invalid char found while deserializing'. – S.N Sep 12 '20 at 12:00

0 Answers0