On Mon, Jul 31, 2017 at 11:56 AM, Ramesh <[email protected]> wrote:
> Hi,
>
> I have requirement to get root element from JSON document which I use for
> other manipulations. My applications have different apis(heterogeinus) some
> includes root element and some do not include root element in the JSON
> payload.
> SO I need to inspect the payload and check if it has root element, then plan
> to set
>
> jacksonObjectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
>
> for e.g;
> JavaType javaType = getJavaType(type, contextClass);
> Annotation rootAnnotation =
> javaType.getRawClass().getAnnotation(JsonRootName.class);
> if(rootAnnotation != null){
>
> this.getObjectMapper().enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
> }
>
> The problem is, some of the JSON objects do not have JsonRoot annotation. So
> I am always getting the rootAnnotation as null though root element is
> included in the JSON payload.
> Is there anyway to check dynamically, weather root element included in
> payload(generic way)?
To be honest, I think dynamic cases like this are often better deal
with using 2-phase processing:
first read contents into a `JsonNode`, and then removing root element
if it matches.
But... one possibility could be to try handle wrapping by a
self-referential definition
public class RootValue {
// regular fields, setters/getters
public int value1, value2;
// then "unwrapping" case for, say, wrapper property of name "root"
// (also note: you probably do NOT want a getter, only useful for
deserialization)
public void setRoot(RootValue unwrapped) {
// assign from properties of `unwrapped` -- or, store a reference
}
}
and choice here would be whether to try to unwrap properties within
set method OR to retain reference, and then have another convenience
method for "unwrapping" instance (that is, returning `this` if no
wrapping was observed; or reference to unwrapped instance if it was).
This would, then, work for both
{ "value1", 12,
"value2", 28 }
and
{ "root" : {
"value1" : 12, "value2" : 28 }
}
Does this make sense? I have found that careful use of getters/setters
that are not bound to properties can be used to do minor structural
transformations, conveniently and safely.
I hope this helps,
-+ Tatu +-
>
> Thanks,
>
> --
> You received this message because you are subscribed to the Google Groups
> "jackson-dev" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google Groups
"jackson-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.