3

我正在尝试从 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”值?

4

3 回答 3

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

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

}
于 2012-07-09T13:47:55.253 回答
0

在本用户指南中,您可以找到很多示例:

https://sites.google.com/site/gson/gson-user-guide

于 2012-07-09T13:44:52.910 回答
0

这就是我使用的代码(对我来说效果很好)。

//Initialize the list
Type listType = new TypeToken<ArrayList<YourObject>>(){}.getType();
//Parse
List<YourObject> List= new Gson().fromJson(response, listType);

YourObject 应该是这样的:

public class Category {
    private String URL;
    private String img-src;

    public Category(String URL, String img-src){
        this.URL= URL;
        this.img-src= img-src;
    }
}

问候。

Ps:这样你会得到一个“YourObject”的列表。然后您可以创建以列出一个与 URL 和其他与 img-src

于 2012-07-09T13:35:27.463 回答