まず、この愚かな質問を申し訳ありません。サーバー(Java)からJSONを読んでください
このJSONファイルをサーバーから読み取る方法について、誰でもコードを手伝ってもらえますか?私は、いくつかのチュートリアルを見てから自分のJavaコードを台無しにしました。
[
{
"name": "Coleen Sanford",
"location": {
"latitude": -60.489023,
"longitude": -32.311668
}
},
{
"name": "Bethany Church",
"location": {
"latitude": -1.304805,
"longitude": -80.670287
}
},
{
"name": "Kristy Ware",
"location": {
"latitude": -46.443562,
"longitude": -46.426997
}
},
{
"name": "Avery Navarro",
"location": {
"latitude": 35.719469,
"longitude": -172.783006
}
},
{
"name": "Robyn Cruz",
"location": null
},
{
"name": "Vinson Hays",
"location": null
}
]
これは私のコードです:
/**
* Async task class to get json by making HTTP call
*/
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) {
HttpHandler sh = new HttpHandler();
// 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 = new JSONArray (jsonStr);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("name");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("location");
String latitude = phone.getString("latitude");
String longitude = phone.getString("longitude");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("name", name);
contact.put("latitude", latitude);
contact.put("longitude", longitude);
// adding contact to contact list
contactList.add(contact);
}
} 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();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"name", "latitude",
"longitude"}, new int[]{R.id.name,
R.id.latitude, R.id.longitude});
lv.setAdapter(adapter);
}
}}
使用 'optString'「いくつかの値のcuzがnullのプラス' jsonStr'は –