Store name of root element in Jackson generated JSON

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

Here is my method for serializing an object to 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 in a java object that is generated from an XSD schema but has no annotation @XmlRootElement

. Is there a way to tell Jackson to keep the name of this object?

The following is currently being generated:

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

      

While it should be:

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

      

My class, which I pass as root for the mapper object, 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 annotation @XmlType

? Does anyone know how to solve this?

+3


source to share


2 answers


If you put @XmlRootElement(name="EvaluationType")

at the beginning of a class definition, it should provide a name. Or are you stating that for some reason you cannot add @XmlRootElement

to your class?

Update



Jackson 2 will use the class name for the JSON key if not @XmlRootElement

. 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>

      

+3


source


for version 2.6 use below



ObjectMapper objectMapper = new ObjectMapper();
JaxbAnnotationModule module = new JaxbAnnotationModule();
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE,true);      
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE,true);

      

0


source







All Articles