如果您收到 JSON 响应,我建议您使用 Gson 解析它。只要您可以用一对行解析整个内容,就强烈建议您这样做。请注意,创建一个适当的对象就像执行以下操作一样简单:
YourObject object = gson.fromJson(responseReader, YourObject.class);
或者即使您正在检索项目列表:
Type listType = new TypeToken<List<YourObject>>() {}.getType();
List<YourObject> objects = gson.fromJson(responseReader, listType);
这是一个完全符合您需求的示例
该过程完成后,您将在可访问变量中提供您的对象(或对象列表)。
编辑:
首先你的 Asynctask 应该有以下参数:
public class HttpTask extends AsyncTask<Void, Void, ArrayList<Driver>> {
并且您的 doInBackground 方法需要将该数组传递给您的 onPostExecute:
@Override
protected ArrayList<Driver> doInBackground(Void... params) {
其余的,我在 JSon 解析开始时接受它。
//PARSING JSON DATA
try {
JSONObject json_data;
Driver d;
jArray = new JSONArray(result);
int l = jArray.length();
if(l>0){
ArrayList<Driver> drivers = newArrayListList<Driver>();
for (int i = 0; i < l; i++) {
json_data = jArray.getJSONObject(i);
d = new Driver(json_data.optString("Driver_full_name"), json_data.optString("Drives_for"));
drivers.add(d);
Log.i("work", returnString);
Log.i("dontwork", somethingelse);
}
} catch (JSONException e1) {
Log.d("DB", "Error somewhere");
CurrentSeasonDrivers_DriverName.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(CurrentSeasonDrivers_DriversName, "Could not parse data so shut up", Toast.LENGTH_LONG).show();
}
});
}
return drivers;
}
protected void onPostExecute(ArrayList<Drivers>... drivers) {
Log.i("Google", returnString);
Log.i("Google1", somethingelse);
String firstDriverName = drivers.get(0).name;
String firstDriverDrivesFor = drivers.get(0).drivesfor;
String secondDriverName = drivers.get(1).name;
TextView drivername = (TextView) findViewById(R.id.DriverName);
drivername.setText(firstDriverName);
TextView drivesfor = (TextView) findViewById(R.id.DrivesFor);
drivesfor.setText(firstDriverDrivesFor);
}
有了这个,你的司机的一个对象将完成这个圆圈。
public class Driver{
public String name;
public String drivesfor;
public Driver(String _name, String _drivesfor){
name = _name;
drivesfor = _drivesfor;
}
}
我想你可以从这里接管。让我知道你的进展。