Difference between string scanning and JSON parsing for a JSON string

牧云@^-^@ 提交于 2019-12-11 13:27:15

问题


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:

  1. Add GSON library by adding the following line to the app/build.gradle file: dependencies { compile 'com.google.code.gson:gson:2.4' }
  2. Go to jsonschema2pojo.
  3. Copy and paste the JSON string into the output box.
  4. Select JSON for Source type.
  5. Select None for Annotation style.
  6. Click the Preview button.
  7. Copy and paste the generated classes into your project.
  8. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!