001/*
002 * Copyright 2012-2017 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.boot.jackson;
018
019import java.io.IOException;
020
021import com.fasterxml.jackson.core.JsonGenerator;
022import com.fasterxml.jackson.databind.JsonMappingException;
023import com.fasterxml.jackson.databind.JsonSerializer;
024import com.fasterxml.jackson.databind.SerializerProvider;
025
026/**
027 * Helper base class for {@link JsonSerializer} implementations that serialize objects.
028 *
029 * @param <T> the supported object type
030 * @author Phillip Webb
031 * @since 1.4.0
032 * @see JsonObjectDeserializer
033 */
034public abstract class JsonObjectSerializer<T> extends JsonSerializer<T> {
035
036        @Override
037        public final void serialize(T value, JsonGenerator jgen, SerializerProvider provider)
038                        throws IOException {
039                try {
040                        jgen.writeStartObject();
041                        serializeObject(value, jgen, provider);
042                        jgen.writeEndObject();
043                }
044                catch (Exception ex) {
045                        if (ex instanceof IOException) {
046                                throw (IOException) ex;
047                        }
048                        throw new JsonMappingException(jgen, "Object serialize error", ex);
049                }
050        }
051
052        /**
053         * Serialize JSON content into the value type this serializer handles.
054         * @param value the source value
055         * @param jgen the JSON generator
056         * @param provider the serializer provider
057         * @throws IOException on error
058         */
059        protected abstract void serializeObject(T value, JsonGenerator jgen,
060                        SerializerProvider provider) throws IOException;
061
062}