Java class with many types of ArrayList
I'm new to Android and Android Java and have questions about my server application communication My server always returns JSON output with "code", "message" and "data" like this:
e.g: {"code":200,"msg":"success","data":[{"track_id":123},{"track_id":124},{"track_id":125}]} e.g: {"code":200,"data":[{"type":"car","length":100},{"type":"train","length":500},{"type":"foot","length":3}]}
I want to use this class to process data:
public class ServerResponse { private int code; private String msg; private List<> data; }
But this is my problem I don't want to give "car", "login" and other specific types in the list According to my requirements, I want to create a serverresponse class with list type "car" and another with list type "locations"
Is there a way to use the class serverresponse with multiple types of ArrayLists, or do I have to copy this class multiple times for each list type I want to use?
Sorry, if there is a solution here, but I don't know what I'm looking for For the content I search, I can't find a suitable solution
Best wishes, Michael
Solution
View Java generic types
public class ServerResponse<T> { private int code; private String msg; private List<T> data; }
T can be any type you want, so your list will be of that type Then your getter / setter method can return or accept type T
Now let's assume that your response is for the car object You will
private ServerResponse<Car> mCarResponse = new ServerResponse<>();
Now you can place a method in the serverresponse class like this
public class ServerResponse<T> { private int code; private String msg; private List<T> data; public List<T> getResponSEObjectList(){ return data; } }
You will now get a list < car > object