簡體   English   中英

Android Java從URL解析JSON到對象列表

[英]Android java parse json from url to object list

我想連接到Api網址,檢索json並將所有內容存儲在對象列表中。 這是 url可以作為Json返回的示例 請注意,開頭有一個countpagelast_page 這些是頁面上有多少個項目,您在哪個頁面上以及總共有多少頁面(一頁上最多50個計數)。 不確定的搜索可以輕松返回多達1000頁的結果

我在c#中有這段代碼,它可以完美地工作,但是在搜索並嘗試了很長時間之后,我不知道如何在Android java中重新創建它。

這是api_handler.cs

public class api_Handler
    {
        public static RootObject objFromApi_idToName(string spidyApiUrl, int page){
            RootObject rootObject = null;
            RootObject tempRootObject = null;

            do{
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(spidyApiUrl + "/" + page);

                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream()){
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    var jsonReader = new JsonTextReader(reader);
                    var serializer = new JsonSerializer();
                    tempRootObject = serializer.Deserialize<RootObject>(jsonReader);

                    if (rootObject == null){
                        rootObject = tempRootObject;
                    }
                    else{
                        rootObject.results.AddRange(tempRootObject.results);
                        rootObject.count += tempRootObject.count;
                    }
                }
                page++;
            }

            while (tempRootObject != null && tempRootObject.last_page != tempRootObject.page);
            return rootObject;
        }
}

我在main_form.cs中這樣調用

// url will become = http://www.gw2spidy.com/api/v0.9/json/item-search/ + textbox.text
// full example = http://www.gw2spidy.com/api/v0.9/json/item-search/Sunrise
    string spidyApiUrl = String.Format("{0}{1}/api/{2}/{3}/{4}/{5}", Http, spidyHost, spidyApiVersion, format, spidyApiType, dataId);
    var spidyApi_idByName = api_Handler.objFromApi_idToName(spidyApiUrl, startPage);

當然,構造函數雖然我認為這些問題確實很重要,但要包括在問題中。

public class Result
    {
        public int data_id { get; set; }
        public string name { get; set; }
        public int rarity { get; set; }
        public int restriction_level { get; set; }
        public string img { get; set; }
        public int type_id { get; set; }
        public int sub_type_id { get; set; }
        public string price_last_changed { get; set; }
        public int max_offer_unit_price { get; set; }
        public int min_sale_unit_price { get; set; }
        public int offer_availability { get; set; }
        public int sale_availability { get; set; }
        public int sale_price_change_last_hour { get; set; }
        public int offer_price_change_last_hour { get; set; }
    }

    public class RootObject
    {
        public int count { get; set; }
        public int page { get; set; }
        public int last_page { get; set; }
        public int total { get; set; }
        public List<Result> results { get; set; }
    }

如何將C#中的工作代碼轉換為android java? 還是從頭開始重新制作是個更好的主意(我仍然需要一些指導,因為我已經嘗試了很多次而沒有成功)

也:

在PC上的C#中,這將在理想的可接受時間內運行,對於1000x50的對象可能需要加載1-2秒,這是非常不明確的搜索。 這些非特定的搜索當然可以發生,因為它是由用戶輸入確定的,但是不會經常發生,正常的搜索可能是1頁到50頁。電話是否可以在可接受的時間內執行此操作?

TL; DR連接到api>檢索所有json值>全部存儲在對象列表中>發送回activity.java

在Android中使用AsyncTask

活動:

public class MainActivity extends Activity implements onResponse {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String URL = "http://www.gw2spidy.com/api/v0.9/json/item-search/Sunrise";
    AsyncFetch parkingInfoFetch = new AsyncFetch(this);
    parkingInfoFetch.setOnResponse(this);
    parkingInfoFetch.execute(URL);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);

    return true;
}

@Override
public void onResponse(JSONObject object) {
    Log.d("Json Response", "Json Response" + object);

    ResultClass resultClass = new ResultClass();

    try {
        resultClass.setCount(object.getInt("count"));
        resultClass.setPage(object.getInt("page"));
        resultClass.setLast_page(object.getInt("last_page"));
        resultClass.setTotal(object.getInt("total"));
        JSONArray array = new JSONArray(object.getString("results"));
        for (int i = 0; i < resultClass.getTotal(); i++) {
            JSONObject resultsObject = array.getJSONObject(i);
            resultClass.setData_id(resultsObject.getInt("data_id"));
            resultClass.setName(resultsObject.getString("name"));
            resultClass.setRarity(resultsObject.getInt("rarity"));
            resultClass.setRestriction_level(resultsObject
                    .getInt("restriction_level"));
            resultClass.setImg(resultsObject.getString("img"));
            resultClass.setType_id(resultsObject.getInt("type_id"));
            resultClass.setSub_type_id(resultsObject.getInt("sub_type_id"));
            resultClass.setPrice_last_changed(resultsObject
                    .getString("price_last_changed"));
            resultClass.setMax_offer_unit_price(resultsObject
                    .getInt("max_offer_unit_price"));
            resultClass.setMin_sale_unit_price(resultsObject
                    .getInt("min_sale_unit_price"));
            resultClass.setOffer_availability(resultsObject
                    .getInt("offer_availability"));
            resultClass.setSale_availability(resultsObject
                    .getInt("sale_availability"));
            resultClass.setSale_price_change_last_hour(resultsObject
                    .getInt("sale_price_change_last_hour"));
            resultClass.setOffer_price_change_last_hour(resultsObject
                    .getInt("offer_price_change_last_hour"));

        }

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

}}

AsyncTask類別:

public class AsyncFetch extends AsyncTask<String, Void, JSONObject> {

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

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

public onResponse getOnResponse() {
    return onResponse;
}

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

@Override
protected JSONObject doInBackground(String... params) {
    // TODO Auto-generated method stub
    try {
        HttpGet get = new HttpGet(params[0]);
        HttpClient client = new DefaultHttpClient();

        HttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        jsonObject = new JSONObject(result);
    } 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 jsonObject;
}

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

}

型號類別:

public class ResultClass {

public int data_id;
public String name;
public int rarity;
public int restriction_level;
public String img;
public int type_id;
public int sub_type_id;
public String price_last_changed;
public int max_offer_unit_price;
public int min_sale_unit_price;
public int offer_availability;
public int sale_availability;
public int sale_price_change_last_hour;
public int offer_price_change_last_hour;

public int count;
public int page;
public int last_page;
public int total;

public int getData_id() {
    return data_id;
}

public void setData_id(int data_id) {
    this.data_id = data_id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getRarity() {
    return rarity;
}

public void setRarity(int rarity) {
    this.rarity = rarity;
}

public int getRestriction_level() {
    return restriction_level;
}

public void setRestriction_level(int restriction_level) {
    this.restriction_level = restriction_level;
}

public String getImg() {
    return img;
}

public void setImg(String img) {
    this.img = img;
}

public int getType_id() {
    return type_id;
}

public void setType_id(int type_id) {
    this.type_id = type_id;
}

public int getSub_type_id() {
    return sub_type_id;
}

public void setSub_type_id(int sub_type_id) {
    this.sub_type_id = sub_type_id;
}

public String getPrice_last_changed() {
    return price_last_changed;
}

public void setPrice_last_changed(String price_last_changed) {
    this.price_last_changed = price_last_changed;
}

public int getMax_offer_unit_price() {
    return max_offer_unit_price;
}

public void setMax_offer_unit_price(int max_offer_unit_price) {
    this.max_offer_unit_price = max_offer_unit_price;
}

public int getMin_sale_unit_price() {
    return min_sale_unit_price;
}

public void setMin_sale_unit_price(int min_sale_unit_price) {
    this.min_sale_unit_price = min_sale_unit_price;
}

public int getOffer_availability() {
    return offer_availability;
}

public void setOffer_availability(int offer_availability) {
    this.offer_availability = offer_availability;
}

public int getSale_availability() {
    return sale_availability;
}

public void setSale_availability(int sale_availability) {
    this.sale_availability = sale_availability;
}

public int getSale_price_change_last_hour() {
    return sale_price_change_last_hour;
}

public void setSale_price_change_last_hour(int sale_price_change_last_hour) {
    this.sale_price_change_last_hour = sale_price_change_last_hour;
}

public int getOffer_price_change_last_hour() {
    return offer_price_change_last_hour;
}

public void setOffer_price_change_last_hour(int offer_price_change_last_hour) {
    this.offer_price_change_last_hour = offer_price_change_last_hour;
}

public int getCount() {
    return count;
}

public void setCount(int count) {
    this.count = count;
}

public int getPage() {
    return page;
}

public void setPage(int page) {
    this.page = page;
}

public int getLast_page() {
    return last_page;
}

public void setLast_page(int last_page) {
    this.last_page = last_page;
}

public int getTotal() {
    return total;
}

public void setTotal(int total) {
    this.total = total;
}

}

希望這個能對您有所幫助,

我建議使用改造庫 這將產生非常干凈的代碼,並使添加新端點或模型對象變得非常容易。 使用改造庫,您將執行以下操作:

創建您的POJO進行解析

public class ResponseObject {

    /**
     * Retrofit will use reflection to set the variable values, so you can
     * make them private and only supply getter methods, no setters needed
     */
    public int count;
    public int page;
    public int last_page;
    public int total;
    public List<Result> results;

    class Result {
        public int data_id;
        public String name;
        public int rarity;
        public int restriction_level;
        public String img;
        public int type_id;
        public int sub_type_id;
        public String price_last_changed;
        public int max_offer_unit_price;
        public int min_sale_unit_price;
        public int offer_availability;
        public int sale_availability;
        public int sale_price_change_last_hour;
        public int offer_price_change_last_hour;
    }
}

創建一個API接口

public interface YourWebApi {
    @GET("/item-search/{query}/{page}")
    ResponseObject getItemsList(@Path("query") String query, @Path("page") Integer page, Callback<ResponseObject> callback);
}

創建回調類(可能是內部類,無論您在哪里發出請求)

當異步請求完成時,將調用內部方法

// this Callback<T> interface is from the retrofit package!!!!!
private class CustomCallback<ResponseObject> implements Callback<ResponseObject> {

    /** Successful HTTP response. */
    void success(RepsonseObject responseObject, Response response) {
        List<Result> results = responseObject.results;
        // do something with your results
    }

    /**
     * Unsuccessful HTTP response due to network failure, non-2XX status 
     * code, or unexpected exception.
     */
    void failure(RetrofitError error) {
        // present toast or something if there's a failure
    }
}

創建您的請求

RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint("http://www.gw2spidy.com/api/v0.9/json")
        .build();

YourWebApi api = restAdapter.create(YourWebApi.class);

/** 
 * This is the asynchronous request, from here either success or failure
 * methods of your CustomCallback class will be executed when the request
 * finishes. The JSON will be parsed into the ResponseObject automatically
 * using the gson library based off the variable names in ResponseObject
 * thanks to Java's reflection
 */
api.getItemsList("some query string", 1, new CustomCallback<ResponseObject>()); // second param is page int

如果我犯了一些語法錯誤,請編輯,我現在無法測試!

為此,您將需要服務。 我建議您這樣做:

  1. 從您當前的活動中,致電服務
  2. 將該asych任務的值作為JSON對象返回到活動中
  3. 將JSON解析為所需的所需格式。 在這種情況下,對象。

對於如何使用Asynch Task,一個簡單的Google搜索“ Android Asynch Task Tutorial”就足夠了。

ServiceHandler.java的代碼

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
                              List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}
}

如何在您的活動中使用此ServiceHandler? 您將需要使用Asych Task來調用此服務,該服務將連接到您的API並為您提供JSON結果。

private class GetJSON extends AsyncTask<Void, Void, Void> {

    WeakReference<Activity> mActivityReference;

    public GetJSON(Activity activity){
        this.mActivityReference = new WeakReference<Activity>(activity);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(Activity.this);
        pDialog.setMessage("getting data");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... voids) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if(jsonStr != null) {
            try {
                //Process
                }

            }catch (JSONException e){
                //Process
            }

        }
        else{
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }


        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM