jackson-databind: Exception while deserializing with @JsonRootName

Desirialization does not work when there are multiple nodes available at same level as value provided in the JsonRootName

Note: Wrapper is configured with following:

objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);

Class:

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)

@JsonRootName(value = "response")
public class UserProfile {
  String name;
  String link;
}

Input JSON (which works):

{
  "response": {
    "name": "User one:",
    "link": "Some Link"
  }
}

Input JSON (which does not work)

{
  "response": {
    "name": "User one:",
    "link": "Some Link"
  }, 
  "apiVersion" : 1.0
}

About this issue

  • Original URL
  • State: open
  • Created 8 years ago
  • Comments: 15 (5 by maintainers)

Most upvoted comments

I’m not sure the problem’s been solved. Let me share what I did.

<point>
  <x>1</x>
  </y>2<y>
</point>
{
  "point" : {
    "x" : 1,
    "y" : 2
  }
}

I’m not allowed @JsonRootName and that’s why I defined the following class.

@XmlRootElement
class AbstractType<SELF extends AbstractType<SELF>> {

    @JsonIgnore
    @XmlTransient
    public SELF get() { // should be used for getting the result.
        if (wrapped != null) {
            return wrapped;
        }
        return this;
    }

    @XmlTransient
    @Setter
    @Getter
    private SELF wrapped;
}

class Point extends AbstractType<Point> {

    @JsonProperty("point")
    public Point getWrapped() {
        return super.getWrapped();
    }
}

Above class deserialise both following JSON.

{
  "point" : {
    "x" : 1,
    "y" : 2
  }
}
{
  "x" : 1,
  "y" : 2
}

@pritibiyani No, not really, XML and JSON are NOT identical structurally: there is impedance regarding names. So, following might represent identical logical content:

{ "x" : 1, "y" : 2 }
<point>
  <x>1</x>
  </y>2<y>
</point>

and so any “root name” in case of XML must be for point; and since XML does not allow more than one root element, one can never match anything else.

The original reason to support @JsonRootName (and unwrapping) for json was, however, that some legacy json libraries would map such logical content as

{ "point" : {
   "x" : 1,
   "y" : 2
}}

which is redundant and clumsy, but is easier to convert to/from xml.

I am bit wary of either changing definitions of features involved, or adding a single-use feature. But I can see the point of request itseld.

I will have to think more about handling here: a significant part of hesitation is the fact that I don’t know how involved it would be to allow original code to work as shown, for both XML and JSON cases.

I’ll tag this as 2.10 since behavioral change is involved.