java - JSON 字符串的字符串扫描和 JSON 解析之间的区别

标签 java android json android-fragments string-search

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

这种行为的原因是什么? JSON 解析是否过于密集?为此,建议的走动是什么?

编辑:

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.*

最佳答案

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

使用 jsonschema2pojo 从 JSON 字符串自动生成您需要的 POJO (Java) 类。

步骤:

  1. 通过将以下行添加到 app/build.gradle 文件来添加 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);

关于java - JSON 字符串的字符串扫描和 JSON 解析之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37642963/

相关文章:

java - 单击事件打开带布局的抽屉导航

hibernate - 为 hibernate 3.6 配置 pom.xml

java - AChartEngine中条形图绘制慢

jquery - Facebook 支持 jsoncallback= 吗? (JSONP)

java - 具有继承性的 JPA 映射 View 和表

java - 使用 WebdriverManager 在多个测试线程中注册驱动程序时出错

java - 如何在 Android Studio 中更改提示文本颜色?

android - 在选项卡布局 Activity 中,我的 fragment 在滑动时不会刷新

javascript - 以父子层次结构显示 JSON 数据

javascript - 如何在 HTML 页面上使用 JQuery 显示来自 json 文件的标签?