1

I have a class whose object I'm trying to serialize/deserialize:

public class PlanDetails implements Serializable {

private static final long serialVersionUID = -5344035164109142313L;

    @JsonProperty("reserved_volumes")
    private List<ReservedVolume> reservedVolumes;

    private String description; 

    //getter, setter, toString()

ReservedVolume is defined as:

public class ReservedVolume implements Serializable {

private static final long serialVersionUID = 4157996827172339903L;

@JsonProperty("reserved_volume_projection")
private GeoShape reservedVolumeProjection;

@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssXXX")
@JsonProperty("effective_time_begin")
private Date effectiveTimeBegin;

private String notes;

private Double altitude;

// getter, setter, toString()

Now this GeoShape is an interface with 2 (maybe more in future) implementations. How can I deserialize this? I'm expecting this object as request-body to a REST endpoint. As a List<ReservedVolume> a user should be able to send any combination of the implementations of GeoShape. Need to deserialize this to parse.

Wrote a method :

public static PlanDetails fromJson(String jsonString) {
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    return gson.fromJson(jsonString, new TypeToken<PlanDetails>() {
    }.getType());
}

But getting Interface can't be instantiated! error while deserialization. Any help?

Akeshwar Jha
  • 4,516
  • 8
  • 52
  • 91
  • at the time you deserialize that json, do you know the class of the implementation of GeoShape ?? – ΦXocę 웃 Пepeúpa ツ Jun 02 '17 at 05:19
  • In your case you need to know the exact implementation and use this for the deserializion. The deserializionalways needs the implementation and if you don't know which one it is, but could figure out which it is programatically, I would recommend reading about Jackson and custom deserializers. – Nico Jun 02 '17 at 05:26
  • [how-to-instantiate-a-class-that-contains-abstract-fields](https://stackoverflow.com/questions/5489532/jackson-json-library-how-to-instantiate-a-class-that-contains-abstract-fields) could help you – rayen Jun 02 '17 at 05:39
  • Check out https://stackoverflow.com/questions/18567719/gson-deserializing-nested-objects-with-instancecreator and https://stackoverflow.com/questions/43643447/gson-how-do-i-deserialize-interface-fields-having-class-names – Lyubomyr Shaydariv Jun 02 '17 at 07:02

0 Answers0