[英]store json response in array list
錯誤:未通過值傳遞:(“聯系人”)。 給定的代碼是在數組列表中獲取json格式的數據。我正在android studio中執行此任務。 當我運行下面的代碼時,我可以看到json格式的數據,但未找到“ contact”錯誤。我已將obj和其他聲明的變量進行了更改,但仍然面臨相同的問題。 有什么解決的建議嗎?
這是代碼:
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://services.groupkt.com/state/get/IND/all";
List<JsonBean> listobj = new ArrayList<>();
// ArrayList<HashMap<String, String>> contactList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
Httphanlder sh = new Httphanlder();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
JsonBean jsonbeanobj=new JsonBean();
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
jsonbeanobj.setCountry(c.getString("country"));
jsonbeanobj.setName(c.getString("name"));
jsonbeanobj.setAbbr(c.getString("abbr"));
jsonbeanobj.setArea(c.getString("area"));
jsonbeanobj.setCapital(c.getString("capital"));
listobj.add(jsonbeanobj);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
}
這可能不是該問題的答案,但是通常當我看到人們使用JSONObject..etc時,他們是編程的新手。 我曾經做過同樣的事情:)
看看Gson或Jackson庫,它將為您將json反序列化為Java對象。
然后在該示例中,您可以使用Jackson進行以下操作:
List contacts = Array.asList(mapper.readValue(json, Contact[].class));
public class Contact {
@JsonCreator
public Contact(@JsonProperty("name") name...etc)
this.name = name;
}
}
您需要使用json數組“結果”
更新這行
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.