io.ventu.rpc.amqp.defaults.DefaultSerializer.java Source code

Java tutorial

Introduction

Here is the source code for io.ventu.rpc.amqp.defaults.DefaultSerializer.java

Source

/*
 * Copyright (c) 2015-2016. Ventu.io, Oleg Sklyar and contributors, distributed under the MIT license.
 */

package io.ventu.rpc.amqp.defaults;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.ventu.rpc.exception.EncodingException;
import io.ventu.rpc.util.Serializer;

/**
 * {@code DefaultSerializer} represents a default JSON encoder and decoder based on
 * the Jackson {@code ObjectMapper}.
 */
public class DefaultSerializer implements Serializer {

    private final ObjectMapper jsonMapper;

    /**
     * Construct {@code DefaultSerializer} with a default {@code ObjectMapper}.
     */
    public DefaultSerializer() {
        this(new ObjectMapper());
    }

    /**
     * Construct {@code DefaultSerializer} with a given instance of {@code ObjectMapper}.
     * 
     * @param jsonMapper An instance of {@code ObjectMapper} from fasterxml.
     */
    public DefaultSerializer(ObjectMapper jsonMapper) {
        this.jsonMapper = jsonMapper;
    }

    @Override
    public <T> T decode(byte[] data, Class<T> resultClass) throws EncodingException {
        try {
            return jsonMapper.readValue(data, resultClass);
        } catch (IOException ex) {
            throw new EncodingException("failed to decode JSON", ex);
        }
    }

    @Override
    public byte[] encode(Object value) throws EncodingException {
        try {
            return jsonMapper.writeValueAsBytes(value);
        } catch (JsonProcessingException ex) {
            throw new EncodingException("failed to encode JSON", ex);
        }
    }
}