zeluzel
zeluzel

Reputation: 31

Handle (de)serialization of objects with root node only with annotations in Jackson

Let's say I have a JSON like:

{
  "rootNode": {
    "foo": "bar",
    "lubie": "placki"
  }
}

That I want to represent with class:

@JsonRootName(value = "rootNode")
Class JsonPojo {
  @JsonProperty
  String foo;
  @JsonProperty
  String lubie;
}

Now to use the feature, I need to specifically enable a features in ObjectMapper like so:

ObjectMapper mapper = new ObjectMapper().enable(DeserializationFeature.UNWRAP_ROOT_VALUE).enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

I would like, however, to use some sort of an annotation over the POJO, so that those features are always enabled, when (de)serializing the object. I'm using framework "RestAssured" that does the ObjectMapper creation on it's own, and deserialization of an object representing HTTP response looks like:

JsonPojo responseDeserialized = response.as(JsonPojo.class);

Is the only way to create myself 2 separate, custom serializer and deserializer classes and then add following over the POJO:

@JsonSerialize(using = JsonWithRootElementSerializer.class)
@JsonDeserialize(using = JsonWithRootElementDeserializer.class)

Is there no way for sth like:

@JsonSerialize(withFeature = SerializationFeature.UNWRAP_ROOT_VALUE)
@JsonDeserialize(withFeature = DeserializationFeature.UNWRAP_ROOT_VALUE)

If not, how those (de)serializers should look like to be generic ones, i.e. to work for any possible object with root node?

Upvotes: 0

Views: 15

Answers (0)

Related Questions