mardi 24 décembre 2019

Java: How to structure or pattern a class so that we can map composed Object during Runtime?

Consuming a rest api which is returning json which has some fixed format and other change per endpoint. I am using gson library which maps incoming json to java classes.

So I have following abstract Resource:

@Getter
@Setter
public class AbstractResource {
    @SerializedName("Meta")
    @Expose
    private List<Meta> meta = null;
    @SerializedName("Body")
    @Expose
    private List<AbstractBody> body = null;

AbstractBody has following contents:

public class AbstractBody {
    @SerializedName("Body")
    @Expose
    private Computer computer = null;
    @SerializedName("Links")
    @Expose
    private List<Link> links = null;

AbstractResource is common for all endpoints but In Abstract body, It returns Computer in one endpoint and in other endpoint it returns Licenses and other Endpoint returns Clusters. All comes in Body field of json.So everytime AbstractBody gets changes.

Currently i have to make both classes again and again in different packages. So in main things goes like.

 ComputerResource agreement = gson.fromJson(json, ComputerResource .class);

I want to make common package for both abstractresoource and abstractbody and at run time it should decide which class it should get into.

How can i modify above structure to do that?

Aucun commentaire:

Enregistrer un commentaire