字符串扫描和JSON字符串的JSON解析之间的区别 [英] Difference between string scanning and JSON parsing for a JSON string

查看:157
本文介绍了字符串扫描和JSON字符串的JSON解析之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一个JSON字符串,可以在链接六个评论家中找到.当我使用JSON解析来分隔字符串中的字段时,在asynctask onPostExecute中,每次查看该片段时都会刷新该片段.但是,当我通过获取两个定界符的索引之间的子字符串来使用字符串扫描方法时,如果片段之前已加载,则片段内容不会刷新.

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.

此行为的原因是什么? JSON解析是否过于密集?建议的解决方案是什么?

What would be the cause of this behaviour? Is JSON parsing too intensive as such? What would be the suggested walk around for this?

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

我正在使用默认的Android JSON库org.json.*.

I'm am using the default Android JSON library org.json.*.

推荐答案

而不是手动解析JSON字符串,请尝试使用Google的GSON库,该库可用于将JSON字符串转换为等效的Java目的.

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.

使用jsonschema2pojo从JSON字符串自动生成所需的POJO(Java)类.

Use jsonschema2pojo to auto-generate the POJO (Java) classes you need from your JSON string.

步骤:

    通过在app/build.gradle文件中添加以下行来
  1. 添加GSON库:dependencies { compile 'com.google.code.gson:gson:2.4' }
  2. 转到 jsonschema2pojo .
  3. JSON字符串复制并粘贴到输出框中.
  4. 为源类型选择JSON.
  5. 选择无"作为注释样式.
  6. 单击预览"按钮.
  7. 将生成的类复制并粘贴到您的项目中.
  8. 要自动解析JSON字符串,请使用以下代码:Example example = new Gson().fromJson(json, Example.class);
  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);

这篇关于字符串扫描和JSON字符串的JSON解析之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆