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

net.anthavio.httl.marshall.Jackson1Marshaller Maven / Gradle / Ivy

The newest version!
package net.anthavio.httl.marshall;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import net.anthavio.httl.HttlBodyMarshaller;
import net.anthavio.httl.HttlRequestException;

import org.codehaus.jackson.map.ObjectMapper;

/**
 * Jackson 1.9 org.codehaus.jackson 
 * 
 * @author martin.vanek
 *
 */
public class Jackson1Marshaller implements HttlBodyMarshaller {

	private final ObjectMapper objectMapper;

	public Jackson1Marshaller() {
		this.objectMapper = Jackson1Util.build();
	}

	public Jackson1Marshaller(ObjectMapper mapper) {
		if (mapper == null) {
			throw new IllegalArgumentException("Null ObjectMapper");
		}
		this.objectMapper = mapper;
	}

	public ObjectMapper getObjectMapper() {
		return objectMapper;
	}

	@Override
	public void marshall(Object payload, String mediaType, String charset, OutputStream stream) throws IOException {
		if (!mediaType.contains("json")) {
			throw new HttlRequestException("Cannot mashall into " + mediaType);
		}
		write(payload, stream, charset);
	}

	public void write(Object requestBody, OutputStream stream, String charset) throws IOException {
		//seems to be impossible to instruct Jackson to use another character encoding
		OutputStreamWriter writer = new OutputStreamWriter(stream, charset);
		objectMapper.writeValue(writer, requestBody);
	}

	@Override
	public String toString() {
		return getClass().getSimpleName() + " [objectMapper=" + objectMapper + "]";
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy