Gson在asyntask期间解析

时间:2013-06-27 15:47:11

标签: java android parsing http gson

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

{
  "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"}
  ]
}

我要做的是将所有“Lab”值放在字符串列表中。 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

2 个答案:

答案 0 :(得分: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"个词落入List<String>,您只需要这样做(这是Java基础... ):

List<String> labs = new ArrayList<String>();
for (Categorie c : response.getCaL()) {
   labs.add(c.getName());
}

答案 1 :(得分: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);
}