由网友(澄耗男)分享简介:我试图解析JSON从一个网址,然后将数据添加到一个数组。我现在用的是GSON库。I am trying to parse JSON from a URL to then add data to an array.I am using the GSON library.我的JSON格式如下:My JSON ha...
我试图解析JSON从一个网址,然后将数据添加到一个数组。 我现在用的是GSON库。
I am trying to parse JSON from a URL to then add data to an array. I am using the GSON library.
我的JSON格式如下:
My JSON has the following format:
[
{
"img-src":"http://website.com/images/img1.png",
"URL":"http://google.com"
},
{
"img-src":"http://website.com/images/img2.jpg",
"URL":"http://yahoo.com"
}
]
我想抓住上面的数据在一个单独的线程,我有以下的code:
I want to grab the above data in a separate thread, I have the following code:
public class Async extends AsyncTask<String, Integer, Object>{
@Override
protected String doInBackground(String... params) {
return null;
}
}
我如何去抓住每一个IMG-SRC和URL的价值观?
How do I go about grabbing each "img-src" and "URL" values?
推荐答案
使用这种方法来获取一个数组列表中的数据。
Use this method to fetch your Data in an Array list
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类型类(在这里它的NewsItem)
This should be how you should declare your ArrayList Type class (here its 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;
}
下面是web服务的Util类。
Here is the WebSErvice Util Class.
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;
}
}
相关推荐
最新文章