java - 安卓SDK : Parsing JSON from URL using GSON

标签 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"
   }
]

我想在一个单独的线程中抓取上面的数据,我有如下代码:

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/

相关文章:

java - IntelliJ : Why can't I use a class from external jar

java - 如何在Java中递归解压缩文件?

Android Studio - 推断无效?

android - Activity MainActivity 泄露了最初绑定(bind)在这里的 ServiceConnection azu@42be3310

android - getCid() 返回的 UTRAN 小区标识

java - Eclipse 重构 : change constructor method signature for all subclasses

java - 为什么在使用注释时必须在 hibernate.cfg.xml 中声明每个类?

JavaScript 序列化和方法

java - 将变量放入 json 文本正文中

javascript - 格式化ajax返回的json