Java class, Arraylist with several types

I am new to Android and Java and ask a question about my connection to the server. My server always returns JSON output with "Codes", "Message" and "Data". Like this:

eg: {"code":200,"msg":"success","data":[{"track_id":123},{"track_id":124},{"track_id":125}]} eg: {"code":200,"msg":"success","data":[{"type":"car","length":100},{"type":"train","length":500},{"type":"foot","length":3}]} 

I want to use a class like this to work with data:

 public class ServerResponse { private int code; private String msg; private List<> data; } 

But here is my problem. I do not want to give a specific type, for example, "car", "input", etc. To the list. Depending on my request, I want to create a ServerResponse class with a list like "car", another with a "Location", etc.

Is there a way to use the ServerResponse class with several types of ArrayLists or do I need to copy this class several times for each type of list that I would like to use?

Sorry if there is a solution somewhere, but I don’t know what I need to look for. And for what I was looking for, I could not find a solution for the propeller.

Regards Michael

+7
java android arraylist server-communication
source share
2 answers

Take a look at Java Common Types .

 public class ServerResponse<T> { private int code; private String msg; private List<T> data; } 

T can be any type that you want your list to be like this. Then your getter / setter methods can return or accept type T.

Now let's assume that your answer was for a Car object. Would you do it

 private ServerResponse<Car> mCarResponse = new ServerResponse<>(); 

Now you can put the method in your ServerResponse class as follows.

 public class ServerResponse<T> { private int code; private String msg; private List<T> data; public List<T> getResponseObjectList(){ return data; } } 

Now you will get a List<Car> object.

+5
source share

You can also create a Serverrespone generator.

 public class GenericResponse <T>{ private int code; private String msg; private List<T> data; } 
0
source share

All Articles