-1

我正在做一个请求,它给了我以下答案:

{
  "SuL":[
    {"IdS":"63","Nam":"Quiz1","Cat":"4097"},
    {"IdS":"64","Nam":"6e","Cat":"4099"},
    {"IdS":"65","Nam":"CP","Cat":"4100"},
    {"IdS":"66","Nam":"CE1","Cat":"4098"}
  ],    
  "CaL":[
    {"Cod":"4097","Lab":"Categorie1"},
    {"Cod":"4098","Lab":"Math"},
    {"Cod":"4099","Lab":"Anglais"},
    {"Cod":"4100","Lab":"Géographie"}
  ]
}

我想要做的是将所有“实验室”值放在字符串列表中。SuL 表示服务器上可用对象的列表(我现在对此不感兴趣),CaL 表示类别。

这是我的类别课程:

public class Categorie {

  public String Cod;
  public String Lab;

  public String getCode() {
    return Cod;
  }
  public void setCode(String code) {
    this.Cod = code;
  }
  public String getName() {
    return Lab;
  }
  public void setName(String name) {
    this.Lab = name;
  }
}

这是我的 AsyncTask 执行请求和 Gson 解析:

class DownloadQuizCategory extends AsyncTask<String, String, String> {

  protected String doInBackground(String...uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;
    ByteArrayOutputStream out;
    try {
      response = httpclient.execute(new HttpGet(uri[0]));
      StatusLine statusLine = response.getStatusLine();
      if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
        out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        responseString = out.toString();
      } else {
        // Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
      }
    } catch (ClientProtocolException e) {
      // TODO Handle problems..
    } catch (IOException e) {
      // TODO Handle problems..
    }
    Log.i("AsyncTask", "responseString : " + responseString);
    return responseString;
  }

  @Override
  protected void onPostExecute(String resultat) {
    super.onPostExecute(resultat);
    //PARSING HERE :(
  }
}

这被称为:

new DownloadQuizCategory().execute(URL_category); //where my results are
4

2 回答 2

1

您只需要在您的班级之外创建另一个Categorie班级。像这样的东西:

public class Response {
    private List<Categorie> CaL;
    //getter & setter
}

然后解析您的响应:

Gson gson = new Gson();
Response response = gson.fromJson(resultat, Response.class);

Gson 将自动且静默地将所有值跳过到"SuL"中,因为SuL您的Response类中没有调用任何属性...


编辑:然后,如果您希望将所有"Lab"vlaues 放入 aList<String>中,您只需要这样做(这是 Java 基础知识......):

List<String> labs = new ArrayList<String>();
for (Categorie c : response.getCaL()) {
   labs.add(c.getName());
}
于 2013-06-27T16:13:02.560 回答
0

你必须反序列化你的 Json,试试上面的这些行。您的 JSONArray 实验室应该包含您的“实验室”列表。

@Override
protected void onPostExecute(String resultat)
{
    super.onPostExecute(resultat);
    JSONObject Response = new JSONObject(resultat);
    JSONArray Lab= (JSONArray) Response.get("Lab");
    System.out.print(Lab);
}
于 2013-06-27T16:10:57.307 回答