我一直在研究如何从服务器查询JSON数据并解析它以便在我的应用程序中使用。但是,我发现了许多不同的方法来做同样的事情。我意识到有不同的JSON解析器,所以让我们假设我坚持使用标准解析器。我的主要问题与服务器请求有关。这是我目前的MapActivity代码
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a Progress Dialog
mProgressDialog = new ProgressDialog(MapActivity.this);
mProgressDialog.setTitle("Downloading Data");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Retrieve JSON Objects from the given URL address
jsonarray = JSONFunctions.getJSONfromURL("myurl");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject obj = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("id", String.valueOf(i));
map.put("name", obj.getString("name"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
// Do something with data
mProgressDialog.dismiss();
}
}
如果我的JSON数据的结构看起来很奇怪,那是因为它存储在一个未命名的数组中,所以我不必先创建一个对象。无论如何......我基本上是基于this tutorial。但是,他们有更多的代码。这一切真的有必要吗?我不这么认为。我搜索了更多,发现其他使用一半代码的例子,基本上做了同样的事情。所以我的问题,作为Android程序员的开始,处理JSON数据的最佳做法是什么?谢谢!
JSON文件示例:
[
{
"name": "test",
"lat": "42.01108",
"long": "93.679196"
},
{
"name": "test",
"lat": "42.01108",
"long": "93.679196"
}
]
答案 0 :(得分:0)
@leerob您好,有一段时间我发现自己处于两难境地,但最近我使用了基本类来使Android处理json并且相当不错,我推荐您的一个好习惯就是声明常量json的关键,我有一个例子:
public void insertMovieTypeFromJson(String movieTypeJsonStr) throws JSONException {
final String ID = "id";
final String TYPE = "type";
final String DESCRIPTION = "description";
if (movieTypeJsonStr == null)
return;
try {
JSONArray movieTypeArrayJson = new JSONArray(movieTypeJsonStr);
Vector<ContentValues> cVVector = new Vector<>(movieTypeArrayJson.length());
for (int i = 0; i < movieTypeArrayJson.length(); i++) {
long id;
String type;
String description;
JSONObject movie = movieTypeArrayJson.getJSONObject(i);
id = movie.getLong(ID);
type = movie.getString(TYPE);
description = movie.getString(DESCRIPTION);
ContentValues movieTypeValues = new ContentValues();
movieTypeValues.put(MovieContract.MovieTypeEntry._ID, id);
movieTypeValues.put(MovieContract.MovieTypeEntry.COLUMN_TYPE, type);
movieTypeValues.put(MovieContract.MovieTypeEntry.COLUMN_DESCRIPTION, description);
cVVector.add(movieTypeValues);
}
int inserted = 0;
if (cVVector.size() > 0) {
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
inserted = getContext().getContentResolver().bulkInsert(MovieContract.MovieTypeEntry.CONTENT_URI, cvArray);
}
Log.d(LOG_TAG, "MovieTask Complete. " + inserted + " MovieType Inserted");
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
JSON:
[
{
"id": "1",
"type": "Action & Adventure",
"description": "Action & Adventure"
},
{
"id": "2",
"type": "Animation",
"description": "Animation"
},
{
"id": "3",
"type": "Comedy",
"description": "Comedy"
},
{
"id": "4",
"type": "Terror",
"description": "Terror"
}
]
我希望你觉得它很有用。
答案 1 :(得分:0)
试试这个......
private class TestJSONParsing extends AsyncTask<JSONArray, Void, JSONArray>
{
ArrayList<HashMap<String, String>> arraylist;
HashMap<String, String> map;
@Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = new ProgressDialog(MapActivity.this);
mProgressDialog.setTitle("Downloading Data");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
@Override
protected JSONArray doInBackground(JSONArray... params)
{
return JSONFunctions.getJSONfromURL("myurl");
}
@Override
protected void onPostExecute(JSONArray resultArray)
{
super.onPostExecute(resultArray);
mProgressDialog.dismiss();
if (null != resultArray)
{
int resultLength = resultArray.length();
if (resultLength > 0)
{
try
{
for (int i = 0; i < resultLength; i++)
{
JSONObject jsonObject = resultArray
.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", jsonObject.getString("name"));
arraylist.add(map);
}
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
if (arraylist.size() > 0)
{
SimpleAdapter adapter = new SimpleAdapter(
MapActivity.this, arraylist,
R.layout.your_simple_row, new String[]
{ "id", "name" }, new int[]
{ R.id.nameId, R.id.name });
// bind adapter to your components
listView.setAdapter(adapter);
}
}
} else
{
Toast.makeText(getApplicationContext(), "No data",
Toast.LENGTH_SHORT).show();
}
}
}
快乐的编码......