繁体   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