gervais.b
gervais.b

Reputation: 2347

Deserialize string property to one object

We have a JSON message with one of the properties that we want to convert to a class:

{
   "href": "/a/b/123",
   "name": "Sample"
}
class Item {
  String name;
  ItemHref href;

  // Constructor and getters
}
class ItemHref {
  String value;
  // Constructor and getters
}

We would like to deserialize the href property as an instance of ItemHref. Unfortunately, we cannot find any way to achieve that.

A custom deserializer could be the solution. However, we have many type of "href" and we do not want to create a custom deserializer for all.

Does anyone, know how to deserialize one property to one object with Jackson?

EDIT: We have tried to place @JsonCreator and @JsonProperty on the ItemHref constructor but we got the following error:

failed: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of acme.ItemHref (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (‘/a/b/123’)

Upvotes: 0

Views: 913

Answers (1)

ASamsig
ASamsig

Reputation: 456

You can use Jackson's @JsonCreator and @JsonProperty annotations to specify a custom deserializer for a property in a JSON message.

Here is an example of how you could use these annotations to deserialize the href property in your JSON message as an instance of ItemHref:

    class Item {
      String name;
      ItemHref href;
    
      @JsonCreator
      public Item(@JsonProperty("href") ItemHref href, @JsonProperty("name") String name) {
        this.href = href;
        this.name = name;
      }
      // getters

    }
    
    class ItemHref {
      String value;

      public ItemHref(String value) {
          this.value = value;
      }
      // getters
    }

The @JsonCreator annotation is used to specify a constructor or factory method to be used for creating instances of the class from JSON. The @JsonProperty annotation is used to specify the JSON property that the constructor or factory method parameter is mapped to.

In this example, the Item class has a constructor that takes ItemHref and String parameters. These parameters are annotated with @JsonProperty, which specifies that the href JSON property is mapped to the ItemHref parameter and the name JSON property is mapped to the String parameter.

This allows Jackson to use the constructor to create instances of the Item class from JSON, and to automatically deserialize the href property as an instance of ItemHref.

You can find more information about using Jackson's annotations for custom deserialization in the Jackson documentation.

Upvotes: 2

Related Questions