Skip to content
JonathanO edited this page Apr 2, 2013 · 2 revisions

JsonTypeInfo

Control how inheritance works. When handed JSON we need to somehow work out what derived type to de-serialize it as. When serializing we need to somehow store in the JSON what type we really are. This annotation configures how that happens.

This can be specified both on the class level, and also on a per property basis.

Parameters

  1. use (integer) What value to use as the type discriminator. One of the Id enum values.
  2. include (integer) Where the discriminator should be placed. One of the As enum values.
  3. property (string) Depends on the value of include. When include is PROPERTY then this sets the name of the property to use.
  4. visible (bool) Pass through the value of the discriminator to the de-serialized object. Default false.
  5. defaultImpl (string) Name of a class to instantiate when there wasn't a better class to use. Defaults to this class.

Enums

  • Id

    • CLASS: The full class name (including namespace) is the discriminator value
    • CUSTOM: Not implemented.
    • MINIMAL_CLASS: The class name, without namespace, is the discriminator value
    • NAME: The "name" either from JsonSubTypes, or JsonTypeName is the discriminator
    • NONE: No discriminator value. Good luck.
  • As

    • PROPERTY: Include the discriminator as a property on the object, named by the property parameter.
    • WRAPPER_ARRAY: Wrap the object in a two value array, the first value is the discriminator, the second is the object
    • WRAPPER_OBJECT: Wrap the object in another object with a single property, name is the discriminator, value is the object
    • EXTERNAL_PROPERTY: Include the discriminator in a named property on the object that this object is a property on.

Examples

For Doctrine driven annotations:

<?
/**
 * @JsonTypeInfo(use=JsonTypeInfo::ID_NAME, include=JsonTypeInfo::AS_PROPERTY, property="type")
 * @JsonSubTypes({@JsonSubTypes\Type("Foo"), @JsonSubTypes\Type("Bar")})
 */
class Baz {
}

/**
 * @JsonTypeName("foo")
 */
class Foo extends Baz {
}

/**
 * @JsonTypeName("bar")
 */
class Bar extends Baz {
}

For Weasel driven annotations:

<?
/**
 * @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
 * @JsonSubTypes({@JsonSubTypes\Type("Foo"), @JsonSubTypes\Type("Bar")})
 */
class Baz {
}

/**
 * @JsonTypeName("foo")
 */
class Foo extends Baz {
}

/**
 * @JsonTypeName("bar")
 */
class Bar extends Baz {
}

Back to Annotations list

Clone this wiki locally