我想创建一个包含不同JSON对象的列表。从我的JSON URL我得到一个包含不同类型对象的数组,如:
[ { "类型":0, "的cityName":"柏林&#34 ;, "位置":"德国" }, { "类型":1, "天气":"太阳&#34 ;, "度":10 } ]
对于不同类型的对象我是不同的类。
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;
}
现在我想创建一个包含所有这些对象的列表。就像第一个JSON对象的类型== 0一样,使用JSON对象中的数据创建一个CityObject并将其放入列表中。也许一种方法是通过整个JSON数组,检查每个JSON对象的类型并创建相应类的JAVA对象并将其放在列表中?
但问题是我不知道如何检查JSON对象的类型,然后创建相应类的对象并将其放入列表中。
我遵循了如何使用GSON解析JSON的教程,但教程只是创建了一个类型的列表。
我的类扩展了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();
}
列出cityDeals = Arrays.asList(gson.fromJson(reader,CityDeal [] .class));
这创建了一个只包含一种类型的列表,而不是像通用类一样动态创建。
我希望有人能帮我解决问题。