Java tutorial
/* * Copyright (c) 2015-2016. Ventu.io, Oleg Sklyar and contributors, distributed under the MIT license. */ package io.ventu.rpc.rest.util; 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(String.format("Failed to decode JSON: %s", ex.getMessage()), ex); } } @Override public byte[] encode(Object value) throws EncodingException { try { return jsonMapper.writeValueAsBytes(value); } catch (JsonProcessingException ex) { throw new EncodingException(String.format("Failed to encode JSON: %s", ex.getMessage()), ex); } } }