Android SDK:使用GSON从URL解析JSON

use*_*302 3 java android json gson

我试图从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"
   }
]
Run Code Online (Sandbox Code Playgroud)

我想在一个单独的线程中获取上述数据,我有以下代码:

public class Async extends AsyncTask<String, Integer, Object>{

        @Override
        protected String doInBackground(String... params) {



            return null;
        }


    }
Run Code Online (Sandbox Code Playgroud)

如何获取每个"img-src"和"URL"值?

Som*_*ere 6

使用此方法获取数组列表中的数据

 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;
}
Run Code Online (Sandbox Code Playgroud)

这应该是你应该如何声明你的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; 


}
Run Code Online (Sandbox Code Playgroud)

这是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;
     }

}
Run Code Online (Sandbox Code Playgroud)