问题
Basically, I have a JSON string that could be found at the link Six Critics. When I use JSON parsing to separate fields in the string, in the asynctask onPostExecute
, the fragment is refreshed each time it is viewed. But when I use string scanning methods by getting the substring between the indices of two delimiters, the fragment content is not refreshed if the fragment was loaded before.
What would be the cause of this behaviour? Is JSON parsing too intensive as such? What would be the suggested walk around for this?
EDIT:
JSONObject jsonWholePage = new JSONObject(result);
JSONArray posts = jsonWholePage.optJSONArray("posts");
for(int i=0; I<posts.length(); i++){
JSONObject postObject = posts.getJSONObject(i);
JSONArray cate = postObject.optArray("categories");
int num_cate = cate.length();
String category = cate.getJSONObject(0).optString("title");
String title = postObject.optString("title");
//do something with title and category
I'm am using the default Android JSON library org.json.*
.
回答1:
Instead of parsing the JSON
string manually, try using the Google's GSON
library that can be used to convert a JSON
string into an equivalent Java object.
Use jsonschema2pojo to auto-generate the POJO (Java) classes you need from your JSON
string.
Steps:
- Add
GSON
library by adding the following line to theapp/build.gradle
file:dependencies { compile 'com.google.code.gson:gson:2.4' }
- Go to jsonschema2pojo.
- Copy and paste the
JSON
string into the output box. - Select
JSON
for Source type. - Select None for Annotation style.
- Click the Preview button.
- Copy and paste the generated classes into your project.
- To automatically parse the
JSON
string use the following code:Example example = new Gson().fromJson(json, Example.class);
来源:https://stackoverflow.com/questions/37642963/difference-between-string-scanning-and-json-parsing-for-a-json-string