@JsonCreator

/**
Marker annotation that can be used to define constructors and factory methods as one to use for
instantiating new instances of the associated class.

NOTE:when annotating creator methods(constructors, factory methods) method must either be:
    Single-argument constructor/factory method without JsonProperty annotation for the argument:
    if so, this is so-called "delegate creator", in which case Jackson first binds JSON into type
    of the argument, and then calls creator

    Constructor/factory method where every argument is annotated with either JsonProperty or 
    JacksonInject,to indicate name of property to bind to

Also note that all JsonProperty annotations MUST use actual name(NOT empty String for "default"):
this because Java bytecode does not retain names of method or constructor arguments.     

NOTE: as of JDK 8, some of above changes, with inroduction of names for constructor and method 
parameters
*/

举例

The @jsonCreator annotation is used to tune the constructor/factory used in deserialization.

It's very helpful when we need to deserialize some JSON that doesn't exactly match the target entity we need to get.

Let's look at an example;say we need to deserialize the following JSON:

{
    "id": 1,
    "theName": "My bean"
}

However, there is no theName field in our target entity - there is only a name field. Now - we don't want to change the entity itself - we just need a little more control over the unmarshalling process - by annotating the constructor with @JsonCreator and using the @JsonProperty annotation as well:

public class BeanWithCreator {

    public int id;

    public String name;

    @JsonCreator
    public BeanWithCreator(@JsonProperty("id") int id, @JsonProperty("theName") String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "BeanWithCreator{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

Let's see this in action:

    @Test
    public void test08() throws Exception {
        String json = "{\"id\":1,\"theName\":\"My bean\"}";

        ObjectMapper mapper = new ObjectMapper();
        BeanWithCreator beanWithCreator = mapper.readValue(json, BeanWithCreator.class);
        System.out.println(beanWithCreator);
    }

results matching ""

    No results matching ""