1

I have a simple hierarchy of data objects, which have to be converted to JSON format. Like this:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "documentType")
@JsonSubTypes({@Type(TranscriptionDocument.class), @Type(ArchiveDocument.class)})
public class Document{
  private String documentType;
  //other fields, getters/setters
}

@JsonTypeName("ARCHIVE")
public class ArchiveDocument extends Document { ... }

@JsonTypeName("TRANSCRIPTIONS")
public class TranscriptionDocument extends Document { ... }

Upon JSON parsing I encounter errors like this one: Unexpected duplicate key:documentType at position 339. , because in the generated JSON there are actually two documentType fields.

What should be changed to make JsonTypeName value appear in documentType field, without an error (eg replacing the other value)?

Jackson version is 2.2

manuna
  • 729
  • 14
  • 37
  • 1
    This question as been answered by another guy, the answer is here: https://stackoverflow.com/a/32825241/2683000 – psv Feb 19 '19 at 12:49

1 Answers1

2

Your code doesn't show it, but I bet you have a getter in your Document class for the documentType property. You should annotate this getter with @JsonIgnore like so:

@JsonIgnore
public String getDocumentType() {
    return documentType;
}

There is an implicit documentType property associated with each subclass, so having the same property in the parent class causes it to be serialized twice.

Another option would be to remove the getter altogether, but I assume you might need it for some business logic, so the @JsonIgnore annotation might be the best option.

Marek Radonsky
  • 363
  • 2
  • 7