我遇到一個問題轉換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;
}
}
這裏的一切,我不能看到有關
我應該創建一個新類嗎?我應該改變我的代碼? – 2015-02-23 14:29:03
是的,一個班級,我忘了關鍵字 – Gorcyn 2015-02-23 14:29:58
謝謝它的工作原理 – 2015-02-23 14:32:34