Android Java检索JSON值并将其存储为列表

时间:2015-04-23 14:04:45

标签: java android json list object

我想连接到可以有多个页面的Api链接,并将所有JSON值存储为列表中的对象。

Here is a Api link example with multiple pages, note the number as last being the page you're on.

到目前为止我遇到的问题无法解决。返回类型doInBackground作为构造函数类apiRootObject以及如何反序列化Json结果,它的逻辑原因为什么它不起作用,因为它从AsyncTask扩展但我不知道如何解决这个问题问题或采取什么其他道路。

这是我到目前为止的代码。

在我的Activity.java中调用初始函数

String userSearchRequest = search_activity_data.getString("userSearchRequest");
String URL = "http://www.gw2spidy.com/api/v0.9/json/item-search/" + userSearchRequest + "/";
//Api link example with multiple pages = "http://www.gw2spidy.com/api/v0.9/json/item-search/Iron"
AsyncFetch parkingInfoFetch = new AsyncFetch(this);
parkingInfoFetch.setOnResponse(this);
parkingInfoFetch.execute(URL);

从上面的代码调用我的AsyncFetch.java类 公共类AsyncFetch扩展了AsyncTask {

    public AsyncFetch(Context context) {
        this.context = context;
    }

    private Context context;
    private JSONObject jsonObject;
    private onResponse onResponse;

    public void setOnResponse(onResponse onResponse) {
        this.onResponse = onResponse;
    }

    @Override
    protected apiRootObject doInBackground(String... params) { //Incompatible return type
        // TODO Auto-generated method stub

        apiRootObject apiRootObject = null;
        apiRootObject tempApiRootObject = null;
        int page = 0;

        try {
            do {
                HttpGet get = new HttpGet(params[0] + page);
                HttpClient client = new DefaultHttpClient();
                HttpResponse response = client.execute(get);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);

                //jsonObject = new JSONObject(result);
                tempApiRootObject = /*Deserialize into <RootObject>(result)*/

                if (apiRootObject == null){
                    apiRootObject = tempApiRootObject;
                }
                else{
                    apiRootObject.results.addAll(tempApiRootObject.results);
                    apiRootObject.count += tempApiRootObject.count;
                }
                page++;
            }

            while(tempApiRootObject.last_page != tempApiRootObject.page);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return apiRootObject;
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        this.onResponse.onResponse(result);
    }

    public interface onResponse {
        public void onResponse(JSONObject object);
    }
}

然后回到activity.java中,所有内容都被添加到onResponse函数的列表中。

public void onResponse(JSONObject object) {//Still expecting a JSONObject while I am changing this return type
        Log.i("gw2Log", object.toString());

        apiRootObject resultClass = new apiRootObject();

        try {
            resultClass.setCount(object.getInt("count"));
            resultClass.setPage(object.getInt("page"));
            resultClass.setLast_page(object.getInt("last_page"));
            resultClass.setTotal(object.getInt("total"));
            JSONArray list = new JSONArray(object.getString("results"));

            for (int i = 0; i < resultClass.getCount(); i++) {
                JSONObject resultsObject = list.getJSONObject(i);
                apiResults temp = new apiResults();
                temp.setData_id(resultsObject
                        .getInt("data_id"));
                temp.setName(resultsObject
                        .getString("name"));
                temp.setRarity(resultsObject
                        .getInt("rarity"));
                temp.setRestriction_level(resultsObject
                        .getInt("restriction_level"));
                temp.setImg(resultsObject
                        .getString("img"));
                temp.setType_id(resultsObject
                        .getInt("type_id"));
                temp.setSub_type_id(resultsObject
                        .getInt("sub_type_id"));
                temp.setPrice_last_changed(resultsObject
                        .getString("price_last_changed"));
                temp.setMax_offer_unit_price(resultsObject
                        .getInt("max_offer_unit_price"));
                temp.setMin_sale_unit_price(resultsObject
                        .getInt("min_sale_unit_price"));
                temp.setOffer_availability(resultsObject
                        .getInt("offer_availability"));
                temp.setSale_availability(resultsObject
                        .getInt("sale_availability"));
                temp.setSale_price_change_last_hour(resultsObject
                        .getInt("sale_price_change_last_hour"));
                temp.setOffer_price_change_last_hour(resultsObject
                        .getInt("offer_price_change_last_hour"));
                resultClass.addObject(temp);
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        for(int i = 0; i < resultClass.count; i++) {
            Log.i("gw2Log", resultClass.getObject(i).name);

        }

    }

当然,还有2个构造函数类apiResultsapiRootObject

编辑: 如果您获取问题顶部的链接,则会返回大量JSON值,如果创建了更多新页面,则每个页面可以包含50个这样的结果。

我想连接到此Api链接,并检索所有要返回的值。如果有多个页面,则需要循环遍历所有现有页面,并将这些JSON值添加到完全相同的列表中。

我之前在c#中问了一个类似的问题,在这里我已经有了它的工作但我现在需要在Android Java中完全相同。对于android java我被告知我需要使用AsyncTask来建立连接并在应用程序的后台执行所有这些操作。如果有更好或更简单的方法,请赐教。

3 个答案:

答案 0 :(得分:1)

使用Retrofit可能为时不晚。

答案 1 :(得分:0)

试试这个

    @Override
    protected apiRootObject doInBackground(String... params) { //Incompatible return type
    // TODO Auto-generated method stub

    apiRootObject apiRootObject = null;
    apiRootObject tempApiRootObject = null;
    List<apiRootObject> myList=new ArrayList<apiRootObject>();
    int page = 0;

    try {
    do {
    HttpGet get = new HttpGet(params[0] + page);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(get);
    HttpEntity entity = response.getEntity();
    String result = EntityUtils.toString(entity);

    jsonObject = new JSONObject(result);
 //handling json exceptions
   if(jsonObejct!=null && !jsonObject.isNull("page")&&..){
    tempApiRootObject.page=jsonObject.getString("page");
    tempApiRootObject.last_page=jsonObject.getString("last_page");
    //here we put the results in the tempsApiRootObject
    JSONArray ja = jsonObject.getJSONArray("results");
    for (int i = 0; i < ja.length(); i++) {
    JSONObject c = ja.getJSONObject(i);//this is an item
    int data_id= c.getInt("data_id");
    String name= c.getString("name");
    //the other values
    //here you add them in your arraylist of <apiResults> (*)
    }
    //and here we add the arraylist in (*) to tempApiRootObject
    myList.add(tempApiRootObject);
    /* if (apiRootObject == null){
    apiRootObject = tempApiRootObject;
    }
    else{
    apiRootObject.results.addAll(tempApiRootObject.results);
    apiRootObject.count += tempApiRootObject.count;
    }*/ i didn't understand this
    }page++;
    }

    while(tempApiRootObject.last_page != tempApiRootObject.page);

    } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    return myList// apiRootObject;
    }

和这个

    public void onResponse(List<apiRootObject> myList) {  
    for(int i=0;i++;i<myList.size()){ 
            apiRootObject resultClass =myList.get(i);
//do something 
}
        }

答案 2 :(得分:0)

gson是将json转换为类的最简单方法。

//your class
public class Foo {
  public final int bar;
  public final String bazz;
  public foo(int bar, String bazz) {
    this.bar = bar;
    this.bazz = bazz;
  }
}

//your json
{  "bar" : 4, "bazz" : "interesting content" }

//your gson call
Gson gson = new Gson();
Foo foo = gson.fromJson(json, Foo.class);

您甚至可以执行嵌套对象,并将它们全部反序列化。

public class FooHaver {
    public final String prop1;
    public final Foo foo;
}

//your json
{ "prop1" : "more content", "foo" : { "bar" : 4, "bazz" : "even more content" } }

你也可以将json数组作为数组或任何你想要的类型的java List