gpt4 book ai didi

java - 如何在android中解析这个Json数组

转载 作者:行者123 更新时间:2023-12-01 18:08:23 26 4
gpt4 key购买 nike

我有一个 jsonArray,我想在我的 Android 应用程序中解析它。

数组:-

[
{
"id": 96905,
"category": "topup",
"detail": "Full talktime of Rs.55 + 1 local airtel SMS free for 1 day",
"price": 55,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"validity": "7 days",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 55
},

{
"id": 90397,
"category": "topup",
"price": 510,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 520
},
{
"id": 90399,
"category": "topup",
"price": 1000,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 1020
}]

我的android代码:-

异步任务:-

private class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Android JSON Parse Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}

@Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
JSONObject jo;
JSONArray ja2 = JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam");

for (int i = 0; i < ja2.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jo = ja2.getJSONObject(i);
map.put("rank", jo.getString("price"));
map.put("country", jo.getString("validity"));
map.put("population", jo.getString("talktime"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void args) {
listview = (ListView) findViewById(R.id.listview);
adapter = new ListViewAdapter(MainActivity.this, arraylist);
listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}

JsonFunctions.java

public class JSONfunctions {

public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;

// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}

// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}

try {

jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}

return jArray;
}
}

我得到的错误:-

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:67)
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:39)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)

json 托管 here

我正在关注this学习json解析的教程,但是本教程使用jsonObject,我无法解析json数组。

与此不重复:- Sending and Parsing JSON Objects或者这个How to parse this JSON Array in android?

最佳答案

让我提供一个替代解决方案(某种)。现有代码的一个更简单的版本是:

更新的代码:

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

ProgressDialog mProgressDialog;

ArrayList<HashMap<String, String>> arraylist = new ArrayList<>();

@Override
protected void onPreExecute() {
super.onPreExecute();

mProgressDialog = new ProgressDialog(TestListActivity.this);
mProgressDialog.setTitle("Android JSON Parse Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}

@Override
protected Void doInBackground(Void... params) {

String url = "http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam";

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
okHttpClient.setRetryOnConnectionFailure(true);

Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);

try {
Response response = call.execute();
String strResult = response.body().string();
JSONArray JARoot = new JSONArray(strResult);

for (int i = 0; i < JARoot.length(); i++) {
JSONObject JORoot = JARoot.getJSONObject(i);

HashMap<String, String> map = new HashMap<>();

if (JORoot.has("category") && JORoot.getString("category").equals("topup")) {

if (JORoot.has("id")) {
map.put("id", JORoot.getString("id"));
}

if (JORoot.has("category")) {
map.put("category", JORoot.getString("category"));
}

if (JORoot.has("detail")) {
map.put("detail", JORoot.getString("detail"));
} else {
map.put("detail", null);
}

if (JORoot.has("price")) {
map.put("price", JORoot.getString("price"));
}

/** ADD THE COLLECTED DATA TO THE ARRAY LIST **/
arraylist.add(map); /* THE DATA WILL ONLY BE ADDED IF THE CATEGORY = "topup" */
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}

return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);

ListView testList = (ListView) findViewById(R.id.testList);
TestListAdapter adapter = new TestListAdapter(TestListActivity.this, arraylist);
testList.setAdapter(adapter);

mProgressDialog.dismiss();
}
}

private class TestListAdapter extends BaseAdapter {

Activity activity;

// LAYOUTINFLATER TO USE A CUSTOM LAYOUT
LayoutInflater inflater = null;

// ARRAYLIST TO GET DATA FROM THE ACTIVITY
ArrayList<HashMap<String, String>> arrItem;

public TestListAdapter(Activity activity, ArrayList<HashMap<String, String>> arrItem) {

this.activity = activity;

// CAST THE CONTENTS OF THE ARRAYLIST IN THE METHOD TO THE LOCAL INSTANCE
this.arrItem = arrItem;

// INSTANTIATE THE LAYOUTINFLATER
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
return arrItem.size();
}

@Override
public Object getItem(int position) {
return arrItem.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

// A VIEWHOLDER INSTANCE
ViewHolder holder;

// CAST THE CONVERTVIEW IN A VIEW INSTANCE
View vi = convertView;

// CHECK CONVERTVIEW STATUS
if (convertView == null) {
// CAST THE CONVERTVIEW INTO THE VIEW INSTANCE vi
vi = inflater.inflate(R.layout.test_item, null);

// INSTANTIATE THE VIEWHOLDER INSTANCE
holder = new ViewHolder();

/***** CAST THE LAYOUT ELEMENTS *****/

/* TOP (PRIMARY) ELEMENTS */
holder.txtPrice = (TextView) vi.findViewById(R.id.txtPrice);
holder.txtDetail = (TextView) vi.findViewById(R.id.txtDetail);

// SET THE TAG TO "vi"
vi.setTag(holder);
} else {
// CAST THE VIEWHOLDER INSTANCE
holder = (ViewHolder) vi.getTag();
}

if (arrItem.get(position).get("price") != null) {
String strPrice = arrItem.get(position).get("price");
holder.txtPrice.setText("PRICE: " + strPrice);
}

if (arrItem.get(position).get("detail") != null) {
String strDetail = arrItem.get(position).get("detail");
holder.txtDetail.setText("DETAIL: " + strDetail);
} else {
holder.txtDetail.setText("DETAIL: NA");
}

return vi;
}

private class ViewHolder {

/* TOP (PRIMARY) ELEMENTS */
TextView txtPrice;
TextView txtDetail;
}
}

为了完整起见,我还包含了适配器的代码。这是一个简单的实现。请根据您的要求进行清理/优化/自定义。

  1. 这段代码在发布之前已经过测试(请参阅底部的日志屏幕截图)
  2. 这使用 OkHttp library 。将此 compile 语句添加到模块 gradle 文件的 dependencies 部分:compile 'com.squareup.okhttp:okhttp:2.5.0'。检查更新版本的链接。
  3. 示例代码使用 if 语句,考虑到并非每个记录都具有相同的节点集。

enter image description here

enter image description here

关于java - 如何在android中解析这个Json数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34652015/

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