使用此方法在数组列表中获取您的数据
public ArrayList<NewsItem> getNews(String url) {
ArrayList<NewsItem> data = new ArrayList<NewsItem>();
java.lang.reflect.Type arrayListType = new TypeToken<ArrayList<NewsItem>>(){}.getType();
gson = new Gson();
httpClient = WebServiceUtils.getHttpClient();
try {
HttpResponse response = httpClient.execute(new HttpGet(url));
HttpEntity entity = response.getEntity();
Reader reader = new InputStreamReader(entity.getContent());
data = gson.fromJson(reader, arrayListType);
} catch (Exception e) {
Log.i("json array","While getting server response server generate error. ");
}
return data;
}
这应该是你应该如何声明你的 ArrayList Type 类(这里是它的 NewsItem)
import com.google.gson.annotations.SerializedName;
public class NewsItem {
@SerializedName("title")
public String title;
@SerializedName("content")
public String title_details;
@SerializedName("date")
public String date;
@SerializedName("featured")
public String imgRawUrl;
}
这是 WebSERvice 实用程序类。
public class WebServiceUtils {
public static HttpClient getHttpClient(){
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 50000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 50000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
return httpclient;
}
}