gpt4 book ai didi

java - Android java从url解析json到对象列表

转载 作者:太空狗 更新时间:2023-10-29 16:35:43 25 4
gpt4 key购买 nike

我想连接到一个 Api url,检索 json 并将所有内容存储在一个对象列表中。 Here is an example 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 页。手机是否能够在可接受的时间内执行此操作?

长话短说连接到 api > 检索所有 json 值 > 将所有值存储在对象列表中 > 发送回 activity.java

最佳答案

在 Android 中使用 AsyncTask

Activity :

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

}}

异步任务类:

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

希望对你有帮助

关于java - Android java从url解析json到对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29582639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com