Search code examples
javajakarta-eejaxbjacksonjava-ee-6

What is the difference between @XMLValue and @JsonValue


@JsonValue javadoc states: "Marker annotation similar to javax.xml.bind.annotation.XmlValue". Why is it similar and what are the differences?

I am asking this as a newbie in JAXB, because the javadoc is too cryptic so I can't find the real intent of both, and why @JsonValue is not available in the Java EE spec since it enables us to properly serialize an object into a string (see here for context)


Solution

  • @JsonValue is a Jackson annotation (Jackson is an open source JSON-binding library) and @XmlValue is a JAXB (JSR-222) annotation.

    @JsonValue javadoc states: "Marker annotation similar to javax.xml.bind.annotation.XmlValue". Why is it similar and what are the differences?

    I don't believe there are any differences in terms of Jackson behaviour.

    I can't find the real intent of both

    There are atleast a couple of reasons Jackson supports the JAXB annotations in addition to its own:

    1. The JAXB annotations are included in Java SE 6 and above, so if you use them you aren't introducing any compile time dependencies on the Jackson libraries into your domain model.
    2. You may be mapping the same Java model to both XML and JSON, so you may be able to get away with only one set of metadata on your classes using the JAXB annotations for both.
    3. Some people are using JAXB with Jettison or StAXON to read/write JSON. Since these models are already JAXB annotated, Jackson supporting these annotations makes it easier to transition those users to Jackson.

    why @JsonValue is not available in the Java EE spec

    JAXB is part of Java EE, and Jackson is not. A JSON-Binding JSR (JSR-367) will be part of Java EE 8 (which hopefully Jackson will participate in and implement).


    UPDATE

    "I don't believe there are any differences in terms of Jackson behaviour.". In the link I posted above there is a difference, because if I use @JsonValue in a toString() method it is used to serialize the class as string, but if I use @XmlValue in the same method nothing happens. See here

    Okay there is at least one difference if Jackson supports @JsonValue on the toString() method, but not @XmlValue. It is not valid in JAXB to put @XmlValue on the toString() method so this is probably why Jackson does not support it there.

    Note:

    To use any JAXB annotations with Jackson you need to enable this capability: