Feature: Allow using Arbitrary Constructor or Factory Method for instantiation

(see Jira entry JACKSON-33 for details)

Prior to version 1.2 Jackson required use of the "default constructor" (no-arguments constructor) for instantiating all POJO/bean types, and then setting all values using "setter" methods (or starting with Jackson 1.1, direct field access).

But with 1.2 and above it is possible to annotate alternative "Creator" (constructor or factory method) to use.

A simple example of a Constructor-based Creator is

public class Name {
  private final String givenName, familyName;

 @JsonCreator
  public Name(@JsonProperty("givenName") String g, @JsonProperty("familyName") String f) {
    givenName = g;
    familyName = f;
  }
  public String getGivenName() { return givenName; }
  public String getFamilyName() { return familyName; }

or, with a Factory-based Creator

public class Name
{
  @JsonCreator
  public static Name createName(@JsonProperty("givenName") String g, @JsonProperty("familyName") String f) {
    // do some initialization?
    return new Name(g, f);
  }
  // ...

Different kinds of Creators

There are actually two main types of creator methods, indicated with slightly differing annotations:

1. Property-based creators (example shown above) 2. Delegate-based creators; in which JSON is first bound to a known intermediate ("delegate") value; and this value is passed to a single-argument creator.

Property-based creators

[add full explanation]

Delegate-based creators

[add full explanation]

See Also

One feature that complements this nicely is Mix-in Annotations; the main benefit being that you can use existing constructors and factory methods of third-party libraries, even if you can not modify classes themselves.


CategoryJackson

JacksonFeatureCreators (last edited 2011-07-04 23:48:01 by TatuSaloranta)

Copyright ©2009 FasterXML, LLC