GSON Response Abstract Renewal Refresh

I am making a simple HTTP GET request with a modification and trying to map the json response to my model. The fact is that json returns an array of multiple Shapes, Shape is an abstract class, so it can be a square, a circle, etc. Each figure has its own specified model, so different fields. How can I map this Shape array to a model?

Web service json response

{
  "requestId": 0,
  "totalShapes": 2,
  "shapes": [
    {
      "circle": {
        "code": 1,
        "radius": 220
        "color" : "blue"
      }
    },
    {
      "square": {
        "code": 1,
        "size": 220
      }
    }
  ]
}

Display of the main results:

public class Result {
  @SerializedName("requestId") private int requestId;
  @SerializedName("totalShapes") private int totalShapes;
  @SerializedName("shapes") private List<Shape> shapes;
}

Abstract class:

public abstract class Shape implements Serializable {
}

A circle:

public class Circle {
  @SerializedName("code") private int code;
  @SerializedName("radius") private int radius;
  @SerializedName("color") private String color;
  // + getters...
}

Square:

public class Square {
  @SerializedName("code") private int code;
  @SerializedName("size") private int size;
  // + getters...
}
+4
source share
1 answer

, factory. .

class ShapeDeserializer implements JsonDeserializer<Shape> {
    @Override
    public Shape deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        Map.Entry<String, JsonElement> entry = json.getAsJsonObject().entrySet().iterator().next();
        switch(entry.getKey()) {
            case "circle":
                return context.deserialize(entry.getValue(), Circle.class);
            case "square":
                return context.deserialize(entry.getValue(), Square.class);
            default:
                throw new IllegalArgumentException("Can't deserialize " + entry.getKey());
        }
    }
}

Gson gson = 
    new GsonBuilder().registerTypeAdapter(Shape.class, new ShapeDeserializer())
                     .create();

:

Result result = gson.fromJson(myJson, Result.class);
//Result{requestId=0, totalShapes=2, shapes=[Circle{code=1, radius=220, color='blue'}, Square{code=2, size=220}]}

, Class.forName ( ).

:

  • code Shape ,
  • , , . JsonObject, "", . ( RFC - ), .
+3

Source: https://habr.com/ru/post/1618338/


All Articles