JSON object serialisation / deserialisation

There are two object serialisation/deserialisation libraries used in Zcore:

  • XStream
  • Jackson

Jackson

To ignore a field from serialisation, add the following annotation to the field:

    @JsonIgnore
    public String getSyncFormat() {
        String syncFormat = Constants.SYNC_FORMAT;
        return syncFormat;
    }

Pretty-print:

        mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);

Don't output null values:

        mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

Ignore Unknown fields when deserialising an object:

public static Object getOneJackson(String fileName, Class clazz) throws IOException, FileNotFoundException {
        //XStream xstream = new XStream();
        //HierarchicalStreamDriver driver= null;
        ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
        mapper.getDeserializationConfig().addHandler(new JacksonProblemHandler());
        //mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        Object object = null;
        try {
            object = mapper.readValue(new File(fileName), clazz);
        } catch (JsonMappingException e) {
            log.debug(e);
        }
        return object;
    }

    final static class JacksonProblemHandler extends DeserializationProblemHandler
    {
        public boolean handleUnknownProperty(DeserializationContext ctxt, JsonDeserializer<?> deserializer,
                Object bean, String propertyName)
        throws IOException, JsonProcessingException
        {
            JsonParser jp = ctxt.getParser();

            // very simple, just to verify that we do see correct token type
            log.debug("Unknown property: " + propertyName+":"+jp.getCurrentToken().toString() + " in class: "
 + bean.getClass().getSimpleName() );
            // Yup, we are good to go; must skip whatever value we'd have:
            jp.skipChildren();
            return true;
        }
    }