Gson - 从 Json 转换为 List<>

Gson - Convert from Json to List<>

我在将 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);
    }
}

我的问卷class:

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;
    }
}

这是我看不出有什么问题的所有内容

在这个JSON中,你得到了一个{Code, Label}对象的列表,但是在List 属性一个对象中。

您首先需要将此列表封装在另一个对象中。 如:

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

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

您需要另一个 class 来映射完整结果

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

    @SerializedName("Return")
    private Integer return1;

    //... getters and setters
}

然后您的类型需要绑定到 "MyJson" 或任何您命名的 class。

我假设它是您要映射到 'qstList' 的列表部分。如果是这样,那么您需要先从 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);