Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep root element name in JSON generated by Jackson

Tags:

java

json

jackson

I am using Jackson 1.9.7 to generated some JSON from my Java objects.

Here is my method to serialize an object to a JSON:

public String constructJson(Object object)
        throws EvaluationException {
    try {

        objectMapper.setSerializationConfig(
                objectMapper.getSerializationConfig()
                        .withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL)
                        .withSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY)
                        .with(SerializationConfig.Feature.WRAP_ROOT_VALUE)
        );

        return objectMapper.writeValueAsString(object);

    } catch (IOException e) {
        LOGGER.error("Error", e);
        throw new EvaluationException("Error", e);
    }
}

I am passing the java object which is generated from the XSD schema but it does not have the @XmlRootElement annotation. Is there any way to tell Jackson to keep the name of that object?

At the moment what it generates is:

{"": {
    "generatedId": "EA7EB141D9454433B5E24F374BF25118",....

While it should be:

{"theNameOfTheRoot": {
    "generatedId": "EA7EB141D9454433B5E24F374BF25118",....

My class that I am passing as root to object mapper looks like this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EvaluationType", propOrder = {
    "generatedId",
    "style",
    "status",
    "candidate",
    "texts",
    "evaluationParts"
})
public class EvaluationType {
   .....
}

So maybe there is a way to tell Jackson to take the name from the @XmlType annotation? Does anybody knows how to solve this?


1 Answers

If you put an @XmlRootElement(name="EvaluationType") at the top of your class definition it should provide the name. Or are you stating that you cannot add an @XmlRootElement to your class for some reason?

Update

Jackson 2 will use the class name for the JSON key if there is no @XmlRootElement available. Jackson 2 requires a new set of maven dependencies, specifically:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.1.3</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.1.2</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.1.3</version>
</dependency>

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!