All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.ddth.commons.serialization.JsonSerDeser Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
package com.github.ddth.commons.serialization;

import java.nio.charset.Charset;

import com.github.ddth.commons.utils.SerializationUtils;

/**
 * This implementation of {@link ISerDeser} utilizes JSON for
 * serializing/deserializing.
 * 
 * @author Thanh Nguyen 
 * @since 0.5.0
 */
public class JsonSerDeser implements ISerDeser {

    private final static Charset UTF8 = Charset.forName("UTF-8");

    /**
     * {@inheritDoc}
     */
    @Override
    public byte[] toBytes(Object obj) throws SerializationException {
        return toBytes(obj, null);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public byte[] toBytes(Object obj, ClassLoader classLoader) throws SerializationException {
        String json = SerializationUtils.toJsonString(obj, classLoader);
        return json != null ? json.getBytes(UTF8) : null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public  T fromBytes(byte[] data, Class clazz) throws DeserializationException {
        return fromBytes(data, clazz, null);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public  T fromBytes(byte[] data, Class clazz, ClassLoader classLoader)
            throws DeserializationException {
        String json = data != null ? new String(data, UTF8) : null;
        return SerializationUtils.fromJsonString(json, clazz, classLoader);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy