org.switchyard.serial.jackson.format.JSONJacksonSerializer Maven / Gradle / Ivy
/*
* Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.switchyard.serial.jackson.format;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.SerializationConfig;
import org.switchyard.common.io.CountingOutputStream;
import org.switchyard.serial.BaseSerializer;
import org.switchyard.serial.FormatType;
/**
* A Jackson serializer that performs {@link FormatType.JSON} serialization/deserialization.
*
* @author David Ward <[email protected]> © 2012 Red Hat Inc.
*/
public final class JSONJacksonSerializer extends BaseSerializer {
private static final ObjectMapper OBJECT_MAPPER;
static {
JsonFactory jsonFactory = new JsonFactory();
jsonFactory.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
jsonFactory.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
OBJECT_MAPPER = new ObjectMapper(jsonFactory);
OBJECT_MAPPER.enableDefaultTyping();
OBJECT_MAPPER.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);
}
/**
* Default constructor.
*/
public JSONJacksonSerializer() {
super(FormatType.JSON);
}
/**
* {@inheritDoc}
*/
@Override
public int serialize(T obj, Class type, OutputStream out) throws IOException {
out = new CountingOutputStream(new BufferedOutputStream(out, getBufferSize()));
try {
ObjectWriter writer = OBJECT_MAPPER.writerWithType(type);
if (isPrettyPrint()) {
writer = writer.withDefaultPrettyPrinter();
}
writer.writeValue(out, obj);
} finally {
if (isCloseEnabled()) {
out.close();
}
}
return ((CountingOutputStream)out).getCount();
}
/**
* {@inheritDoc}
*/
@Override
public T deserialize(InputStream in, Class type) throws IOException {
T obj;
try {
obj = OBJECT_MAPPER.readValue(in, type);
} finally {
if (isCloseEnabled()) {
in.close();
}
}
return obj;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy