1 package com.fasterxml.jackson.databind; 2 3 import java.io.IOException; 4 5 import com.fasterxml.jackson.core.*; 6 import com.fasterxml.jackson.databind.jsontype.TypeSerializer; 7 8 /** 9 * Interface that can be implemented by objects that know how to 10 * serialize themselves to JSON, using {@link JsonGenerator} 11 * (and {@link SerializerProvider} if necessary). 12 *<p> 13 * Note that implementing this interface binds implementing object 14 * closely to Jackson API, and that it is often not necessary to do 15 * so -- if class is a bean, it can be serialized without 16 * implementing this interface. 17 *<p> 18 * Note that while it is possible to just directly implement {@link JsonSerializable}, 19 * actual implementations are strongly recommended to instead extend 20 * {@link JsonSerializable.Base}. 21 */ 22 public interface JsonSerializable 23 { 24 /** 25 * Serialization method called when no additional type information is 26 * to be included in serialization. 27 */ serialize(JsonGenerator gen, SerializerProvider serializers)28 public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException; 29 30 /** 31 * Serialization method called when additional type information is 32 * expected to be included in serialization, for deserialization to use. 33 *<p> 34 * Usually implementation consists of a call to {@link TypeSerializer#writeTypePrefix} 35 * followed by serialization of contents, 36 * followed by a call to {@link TypeSerializer#writeTypeSuffix}). 37 * Details of the type id argument to pass depend on shape of JSON Object used 38 * (Array, Object or scalar like String/Number/Boolean). 39 *<p> 40 * Note that some types (most notably, "natural" types: String, Integer, 41 * Double and Boolean) never include type information. 42 */ serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer)43 public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, 44 TypeSerializer typeSer) throws IOException; 45 46 /** 47 * Base class with minimal implementation, as well as couple of extension methods 48 * that core Jackson databinding makes use of. 49 * Use of this base class is strongly recommended over directly implementing 50 * {@link JsonSerializable}. 51 * 52 * @since 2.6 53 */ 54 public abstract static class Base implements JsonSerializable 55 { 56 /** 57 * Method that may be called on instance to determine if it is considered 58 * "empty" for purposes of serialization filtering or not. 59 */ isEmpty(SerializerProvider serializers)60 public boolean isEmpty(SerializerProvider serializers) { 61 return false; 62 } 63 } 64 } 65