【发布时间】:2016-06-20 10:57:09
【问题描述】:
所以我关注了这个tutorial,它有这个方法。
new AsyncTask<Void,Void,Void>(){
@Override
protected Void doInBackground(Void... voids) {
Reader reader=API.getData("http://beta.json-generator.com/api/json/get/DiIRBM4");
Type listType = new TypeToken<ArrayList<DoctorBean>>(){}.getType();
beanPostArrayList = new GsonBuilder().create().fromJson(reader, listType);
postList=new StringBuffer();
for(DoctorBean post: beanPostArrayList){
postList.append("\n heroName: "+post.getHeroName()+"\n realName: "+post.getRealName()+"\n\n");
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.d("JSON Result ", postList.toString());
}
}.execute();
日志结果只会显示这些值。
JSON 结果:
heroName: null realName: null
heroName: null realName: null
heroName: null realName: null
这是我的 JSON 数据
[
{
"heroName": "Dr. Strange",
"realName": "Stephen Strange"
},
{
"heroName": "Spider-Man",
"realName": "Peter Paker"
},
{
"heroName": "Captain America",
"realName": "Stever Rogers"
}
]
这是我的数据模型
import com.google.gson.annotations.SerializedName;
public class DoctorBean {
@SerializedName("heroName")
private String heroName;
@SerializedName("realName")
private String realName;
public DoctorBean(String heroName, String realName) {
this.heroName = heroName;
this.realName = realName;
}
public String getHeroName() {
return heroName;
}
public void setHeroName(String heroName) {
this.heroName = heroName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
}
这是我的 API 类
public class API {
private static Reader reader=null;
public static Reader getData(String SERVER_URL) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
reader = new InputStreamReader(content);
} else {
// Log.e("error:", "Server responded with status code: "+ statusLine.getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return reader;
}
}
我注意到日志结果显示 3 行,所以我认为它能够正确获取数组的长度。但是数据方面,都是空的。
【问题讨论】:
-
您正在尝试获取 json 数据的链接是为您的 json 提供不同的 json。所以你需要根据真实的 json 响应创建 POJO 类。
标签: java android arrays json gson