JiKra
JiKra

Reputation: 1790

JSON Serialization and deserialization works differently using ObjectMapper

I have a JSON like this:

{
  "commonObjects": [
    {
      "type": "C",
      "C": "1234567890"
    },
    {
      "type": "C",
      "c": "0987654321"
    },
    {
      "type": "B",
      "b": "ABCDEFGH"
    },
    {
      "type": "A",
      "A": "11111111",
      "AA": "22222222"
    }
  ]
}

All types can be included variable times or there can be only one type only once.

In SpringBoot application I have three classes, extending common class.

public class AObject extends CommonObject {
    @JsonProperty("A")
    private String a;
    @JsonProperty("AA")
    private String aa;
}
public class BObject extends CommonObject {
    @JsonProperty("B")
    private String b;
}
public class CObject extends CommonObject {
    @JsonProperty("C")
    private String c;
}
public class CommonObject {
    private String type;
}
public class CommonObjects {
    List<CommonObject> commonObjects;
}

Than I have two methods to serialize and deserialize it.

return objectMapper.writeValueAsString(commonObjects);
...
return objectMapper.readValue(jsonValue, CommonObjects.class);

While testing serialization is OK. But deserialization doesn't work in default this way. So I modified CommonObject like this:

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    property = "type",
    visible = true)
@JsonSubTypes({
    @JsonSubTypes.Type(value = AObject.class, name = "A"),
    @JsonSubTypes.Type(value = BObject.class, name = "B"),
    @JsonSubTypes.Type(value = CObject.class, name = "C")
})
public class CommonObject {
  private String type;
}

Now, deserialization works OK, but serialization doesn't. Property type is included twice in json value.

Is there any way to handle this particular problem or do I have to write myself custom deserializer?

Upvotes: 1

Views: 762

Answers (1)

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

There are two issues in your CommonObjectclass which need to be fixed.

  • Remove the visible = true (thus defaulting to visible = false).
    This means the type from JSON input is not deserialized to a Java type property.
  • Remove the property private String type;
    This is because in JSON output you want the type only according to your @JsonTypeInfo and @JsonSubTypes, but not also serialized from a Java type property.

Upvotes: 1

Related Questions