001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.component.jackson;
018
019 import java.io.InputStream;
020 import java.io.OutputStream;
021 import java.util.HashMap;
022 import java.util.Map;
023
024 import org.apache.camel.Exchange;
025 import org.apache.camel.spi.DataFormat;
026 import org.codehaus.jackson.map.ObjectMapper;
027
028 /**
029 * A <a href="http://camel.apache.org/data-format.html">data format</a> ({@link DataFormat})
030 * using <a href="http://jackson.codehaus.org/">Jackson</a> to marshal to and from JSON.
031 */
032 public class JacksonDataFormat implements DataFormat {
033
034 private final ObjectMapper objectMapper;
035 private Class<?> unmarshalType;
036
037 /**
038 * Use the default Jackson {@link ObjectMapper} and {@link Map}
039 */
040 public JacksonDataFormat() {
041 this(new ObjectMapper(), HashMap.class);
042 }
043
044 /**
045 * Use the default Jackson {@link ObjectMapper} and with a custom
046 * unmarshal type
047 *
048 * @param unmarshalType the custom unmarshal type
049 */
050 public JacksonDataFormat(Class<?> unmarshalType) {
051 this(new ObjectMapper(), unmarshalType);
052 }
053
054 /**
055 * Use a custom Jackson mapper and and unmarshal type
056 *
057 * @param mapper the custom mapper
058 * @param unmarshalType the custom unmarshal type
059 */
060 public JacksonDataFormat(ObjectMapper mapper, Class<?> unmarshalType) {
061 this.objectMapper = mapper;
062 this.unmarshalType = unmarshalType;
063 }
064
065 public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception {
066 this.objectMapper.writeValue(stream, graph);
067 }
068
069 public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
070 return this.objectMapper.readValue(stream, this.unmarshalType);
071 }
072
073 // Properties
074 // -------------------------------------------------------------------------
075
076 public Class<?> getUnmarshalType() {
077 return this.unmarshalType;
078 }
079
080 public void setUnmarshalType(Class<?> unmarshalType) {
081 this.unmarshalType = unmarshalType;
082 }
083
084 public ObjectMapper getObjectMapper() {
085 return this.objectMapper;
086 }
087
088 }