我想连接到Api网址,检索json并将所有内容存储在对象列表中。网址可以作为Json返回的Here is an example。请注意,开头有count
,page
和last_page
。这些是页面上有多少项目,您在哪个页面以及总共有多少页面(1页上最多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&gt;检索所有json值&gt;将所有内容存储在对象列表中&gt;发送回activity.java
答案 0 :(得分:4)
在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;
}
}
希望这会对你有所帮助,
答案 1 :(得分:1)
我建议使用retrofit library。它将产生非常干净的代码,并且可以非常容易地添加新的端点或模型对象。使用改造库,您可以这样做:
创建用于解析的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
如果我犯了一些语法错误,请编辑我现在无法测试这个错误!
答案 2 :(得分:0)
为此你需要服务。这是我建议你应该做的事情:
关于如何使用Asynch Task,一个简单的谷歌搜索“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任务来调用此服务,该服务将连接到您的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();
}
}
}