如果你想使用Gson來解析你的json數據。讓我們試試吧:
首先的,則必須修改JSON是這樣的:
{
"contact":[
{
"key1": "hey1",
"key2": [
{
"key3": "hey2"
}
]
}
]
}
二添加GSON到您的庫和同步的build.gradle:下載here提取出來,並複製/過去gson-2.2.4.gson到libs文件夾。
三創建一些類:
FullContents.java:
public class FullContents {
private List<ObjectKey> contact;
public List<ObjectKey> getContact() {
return contact;
}
public void setContact(List<ObjectKey> contact) {
this.contact = contact;
}
}
ObjectKey.java:
public class ObjectKey {
private String key1;
private List<ObjectKey3> key2;
public List<ObjectKey3> getKey2() {
return key2;
}
public void setKey2(List<ObjectKey3> key2) {
this.key2 = key2;
}
public String getKey1(){
return key1;
}
public void setKey1(String key1){
this.key1 = key1;
}
}
ObjectKey3。Java的:
public class ObjectKey3 {
private String key3;
public String getKey3(){
return key3;
}
public void setKey3(String key3){
this.key3 = key3;
}
}
而且最後,從URL中獲取數據:
private class ParseByGson extends AsyncTask<String,Void,FullContents> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected FullContents doInBackground(String... params) {
FullContents fullContents = null;
try {
URL url=new URL(params[0]);
InputStreamReader reader=new InputStreamReader(url.openStream(),"UTF-8");
fullContents=new Gson().fromJson(reader,FullContents.class);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fullContents;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(FullContents results) {
super.onPostExecute(results);
ObjectKey objectKey = results.getContact().get(0);
Log.e(">>",objectKey.getKey1()+"--");
}
}
你可以把下面的代碼的onCreate:
ParseByGson parseByGson = new ParseByGson();
parseByGson.execute(urlStringHere);
更新:解釋
總是假定JSON在你呈現它時是不可變的,「key2」是一個像「key1」這樣的對象,但它包含另一個對象數組,因此在你的「questions」數組迭代中解析另一個數組,迭代數組在「key2」裏面。 –