我正在尝试从 URL 解析 JSON,然后将数据添加到数组。 我正在使用 GSON 库。
我的 JSON 格式如下:
[
{
"img-src":"http://website.com/images/img1.png",
"URL":"http://google.com"
},
{
"img-src":"http://website.com/images/img2.jpg",
"URL":"http://yahoo.com"
}
]
我想在一个单独的线程中抓取上面的数据,我有如下代码:
public class Async extends AsyncTask<String, Integer, Object>{
@Override
protected String doInBackground(String... params) {
return null;
}
}
我如何获取每个“img-src”和“URL”值?
最佳答案
使用此方法获取数组列表中的数据
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 Util 类。
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;
}
}
关于java - 安卓SDK : Parsing JSON from URL using GSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11396055/