1

For the below code, my nested parameterized object is always deserialized as LinkedTreeMap instead of the original class

I am using GSON for json serializing & deserializing

Here are the models:

Cart containing wrapped items

public class Cart {
  private String id;
  private String owner;

  private List<ItemWrapper> relatedItems;

  .......

  public List<ItemWrapper> getRelatedItems() {
        return relatedItems;
  }
  public void setRelatedItems(List<ItemWrapper> relatedItems) {
    this.relatedItems = relatedItems;
  }
}

Item wrapper

public class ItemWrapper<T> {

  private String type;
  private String decription;

  private T item;

  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
  }

  ........

  public T getItem() {
    return item;
  }

  public void setItem(T item) {
    this.item = item;
  }
}

Car Item ..

public class Car {
  private String model;
  private double price;

  public String getModel() {
    return model;
  }

  .....

  public void setPrice(double price) {
    this.price = price;
  }
}

Book Item ..

public class Book {
  private String name;
  private String mediaType;

  public String getName() {
    return name;
  }

  .....

  public void setMediaType(String mediaType) {
    this.mediaType = mediaType;
  }
}

When I run the below snippet

Cart cart = gson.fromJson(
            "{\"id\":\"id123\",\"owner\":\"Usama\",\"relatedItems\":[{\"type\":\"Book\",\"decription\":\"book item\",\"item\":{\"name\":\"Love\",\"mediaType\":\"pdf\"}},{\"type\":\"Car\",\"decription\":\"car item\",\"item\":{\"model\":\"BMW\",\"price\":500000.0}}]}\n"
                    + "",
            Cart.class);

System.out.println(cart.getClass().getName());
System.out.println(cart.getRelatedItems().get(0).getItem().getClass().getName());

I got that result

model.Cart
com.google.gson.internal.LinkedTreeMap

instead of

model.Cart
model.Book

Any idea how to fix this.

Capricorn
  • 2,061
  • 5
  • 24
  • 31
  • 1
    Did you take a look/try using a custom deserializer? https://stackoverflow.com/questions/6096940/how-do-i-write-a-custom-json-deserializer-for-gson – Capricorn Jul 04 '18 at 18:54
  • Here you go: https://stackoverflow.com/questions/5800433/polymorphism-with-gson. – NiVeR Jul 04 '18 at 19:03
  • Thanks guys, I am trying to avoid custom deserialization as objects are complex and not simple as illustrated in the above code. Unfortunately these examples don't fit in my case. – Usama M. Ali Jul 05 '18 at 14:01

0 Answers0