I want to create a list with different JSON objects. From my JSON URL I get an array with different types of objects like:
[ { "type":0, "cityName":"Berlin", "location":"Germany" }, { "type":1, "weather":"Sun", "degree":10 } ]
For the different types of objects I've different classes.
CityObject.class
public class CityObject {
public CityObject(){}
public int type;
public String cityName;
public String location;
}
WeatherObject.class
public class WeatherObject {
public WeatherObject(){}
public int type;
public String weather;
public int degree;
}
Now I want to create one list with all of these objects. Like if the type of the first JSON object == 0, create a CityObject with the data from the JSON object and put it in the list. Maybe a way is go through the whole JSON Array, check the type of each JSON object and create a JAVA object of the respective class and put it in the list?
But the problem is I don't know how to check the type of the JSON object and then create an object of the respective class and put it in the list.
I followed a tutorial how to parse JSON with GSON but the tutorial just create a list of one type.
My class extends AsyncTask
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpGet linkURL = new HttpGet(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(linkURL);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
List<CityDeal> cityDeals = Arrays.asList(gson.fromJson(reader, CityDeal[].class));
content.close();
handleCityDealsList(cityDeals);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingCityDeals();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingCityDeals();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingCityDeals();
}
List cityDeals = Arrays.asList(gson.fromJson(reader, CityDeal[].class));
This create a list of only one type and not dynamicly, like generic classes.
I hope anyone can help me with my problem.