Gson - 从Json转换为List<>

时间:2015-02-23 13:58:27

标签: android json gson

我在将Json转换为List<>时出现问题,我尝试了不同的解决方案,但没有任何线索

我的json结果如下:

{  
   "Return":0,
   "List":[  
      {  
         "Code":524288,
         "Label":"TEST"
      },
      {  
         "Code":524289,
         "Label":"TEST1"
      },
      {  
         "Code":524290,
         "Label":"TEST2"
      }
   ]
}

我的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    List<Questionaire> qstlist = new ArrayList<Questionaire>();
    try {
        result = new RequestTask().execute("http:/dd.com/categories/current?owner=ccc").get();
        json = new JSONObject(result);

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    GsonBuilder gsonb = new GsonBuilder();
    Gson gson = gsonb.create();
    Type listType = new TypeToken<List<Questionaire>>(){}.getType();
    qstlist = (List<Questionaire>) gson.fromJson(result, listType);
    Questionaire qst = null;
    qst = gson.fromJson(result,  Questionaire.class);

    Toast.makeText(MainActivity.this, "Result "+qstlist.size(), Toast.LENGTH_SHORT).show(); 
}

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

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();
            } 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..
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    }
}

我的问卷类:

public class Questionaire {
    String Code;
    String Label;
    public String getCode() {
        return Code;
    }
    public void setCode(String Code) {
        this.Code = Code;
    }
    public String getLabel() {
        return Label;
    }
    public void setLabel(String Label) {
        this.Label = Label;
    }
}

以下是我能看到的错误

3 个答案:

答案 0 :(得分:1)

您需要另一个映射完整结果的类

public class MyJson {
     @SerializedName("List")
    private List<Questionaire> list;

    @SerializedName("Return")
    private Integer return1;

    //... getters and setters
}

然后您的类型需要绑定到“MyJson”或您为该类命名的任何内容。

答案 1 :(得分:0)

在此JSON中,您将获得{Code,Label}对象的列表,但是在对象的List属性中。

首先需要将此列表封装在其他对象中。 如:

public class QuestionaireList {
  public List<Questionaire> List;
}

List<Questionaire> qsts = gson.fromJson(result,  QuestionaireList.class).List;

答案 2 :(得分:0)

我假设它是您要映射到的列表部分&#39; qstList&#39;。如果是这样,那么你需要先从json的其余部分中提取它:

Gson gson = new Gson();
JsonObject resultObj = gson.fromJson(result, JsonObject.class);
JsonArray jsonList = resultObj.get("List").getAsJsonArray();
Type listType = new TypeToken<List<Questionaire>>(){}.getType();
qstList = gson.fromJson(jsonList, listType);