这是我的主类。可以告诉我为什么它在System.print()中返回null。我使用了Gson
外部库。我在这里做错了。如何显示所有包含
public class PostsActivity extends Activity {
private static final String TAG = "PostsActivity";
private List<Post> posts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostFetcher fetcher = new PostFetcher();
fetcher.execute();
}
private void handlePostsList(List<Post> posts) {
this.posts = posts;
runOnUiThread(new Runnable() {
@Override
public void run() {
for(Post post : PostsActivity.this.posts) {
Toast.makeText(PostsActivity.this, post.TITLE, Toast.LENGTH_SHORT).show();
}
}
});
}
private void failedLoadingPosts() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(PostsActivity.this, "Failed to load Posts. Have a look at LogCat.", Toast.LENGTH_SHORT).show();
}
});
}
private class PostFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "PostFetcher";
public static final String SERVER_URL = "http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php";
@Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
Post po = gson.fromJson(reader, Post.class);
List<Post> posts = Arrays.asList(po);
System.out.println("ID:"+po);
content.close();
handlePostsList(posts);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
}
// Post.java
public class Post {
@SerializedName("id")
public long ID;
public String TITLE;
public String AUTHOR;
public String URL;
@SerializedName("date")
public Date dateCreated;
public String body;
public List<Tag> tags;
public Post() {
}
public String toString() {
return "Student [id=" + ID + ", title="
+ TITLE + ", thumb_url=" + URL
+ ", dt=" + AUTHOR + "]";
}
}
答案 0 :(得分:1)
您需要考虑一些事项。首先,您的字段需要具有正确的 @SerializedName(“”)注释。它表示属性名称(如thumb_url,dt)与JSON中的字段名称不匹配。如果两个名称匹配,则不需要注释。
其次,您需要“解析”从服务器获取的响应到JsonObject,然后读取JsonElement。
以下是您需要的代码:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("yy-d-M hh:mm");
//2014-06-14 02:39:24
//yy-d-M hh:mm
Gson gson = gsonBuilder.create();
List<Post> posts = new ArrayList<Post>();
JsonParser jsonParser = new JsonParser();
JsonObject details = jsonParser.parse(reader).getAsJsonObject();
JsonArray array = details.getAsJsonArray("veg_food");
for ( JsonElement element : array ){
Post post = gson.fromJson(element, Post.class);
posts.add(post);
}
System.out.println("ID:"+ posts);
另外,请务必将Post.java
课程更改为:
@SerializedName("id")
public long ID;
@SerializedName("title")
public String TITLE;
@SerializedName("thumb_url")
public String URL;
@SerializedName("dt")
public Date dateCreated;
希望它有所帮助。
<强> [编辑] 强>
输出: