我正在尝试使用gson库解析巨大的json,我的主要想法是从每个对象中获取一个值并将其保存为String。 This我正在使用的json文件。这是我用来解析json的代码:
public class PostsActivity extends Activity {
private static final String TAG = "PostsActivity";
private List<Post> posts;
public TextView textss;
public int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
textss = (TextView)findViewById(R.id.texts);
PostFetcher fetcher = new PostFetcher();
fetcher.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.posts, menu);
return true;
}
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 + " " + i, 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. bls bls bls " , 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://kylewbanks.com/rest/posts";
@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 {
for ( i = 0; i < 4; i++) {
//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();
List<Post> posts = Arrays.asList(gson.fromJson(reader, Post[].class));
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;
}
}
}
我还在学习,我理解的是所有值都保存在一个大列表中,之后这些值显示在Toast
中。我想要做的是保存字符串中的值,就像我想用json这样:
JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");
如何通过使用Gson库来实现这一目标?
答案 0 :(得分:2)
这就是我想要的尝试。
//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();
//List<Post> posts = Arrays.asList(gson.fromJson(reader, Post[].class));
JsonArray posts = new JsonParser().parse(reader).getAsJsonArray();
// Get first element at index 0
Post post1 = gson.fromJson(posts.get(0).getAsJsonObject(), Post.class);
Log.d(TAG, "post1 .. " + post1.getTitle());
content.close();
//handlePostsList(posts);
首先,我创建了一个Gson JsonArray
。并通过创建新的JsonParser
来分配,将reader
解析为JsonArray
。
然后,您可以通过获取索引0处的元素来提取posts
的第一个元素,并使用相应的Object反序列化。
我为Post
对象使用了set / get,因此我将标题设为post1.getTitle()
。
日志说
post1 ..仅使用开发中禁用Google Analytics 的JavaScript