Contacta con nosotros
contacto@flabo.es

Serializar y deserializar objetos

Teniendo una clase llamada “ConfigForm” con una definición:

public class ConfigForm implements Serializable {

    private static final long serialVersionUID = 565464658767423469L;
    ...
    ...
    ...
}

Utilizamos los siguientes métodos para convertir la representación del objeto en String y viceversa. Se utiliza la implementación de Base64 del kernel de Liferay.

import com.liferay.portal.kernel.util.Base64;

public static String serializeForm(ConfigForm form) throws IOException {
	try {
		ByteArrayOutputStream serializedArrayOutputStream = new ByteArrayOutputStream();
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(serializedArrayOutputStream);
		objectOutputStream.writeObject(form);
		objectOutputStream.close();
		return Base64.encode(serializedArrayOutputStream.toByteArray());
	} catch (IOException e) {
		throw e;
	}
}

public static <T extends ConfigForm> T deserializeForm(String formSerialized) throws IOException, ClassNotFoundException {
	try {
		byte[] formSerializedInBytes = Base64.decode(formSerialized);
		ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(formSerializedInBytes));
		ConfigForm formDeserialized = (ConfigForm) ois.readObject();
		ois.close();
		return (T) formDeserialized;
	} catch (IOException|ClassNotFoundException e) {
		throw e;
	}
}