基本上,我有一个可以在链接 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) 类。
步骤:
- 通过将以下行添加到
app/build.gradle
文件来添加GSON
库:dependencies { compile 'com.google.code.gson:gson :2.4' }
- 转到 jsonschema2pojo .
- 将
JSON
字符串复制并粘贴到输出框中。 - 为源类型选择
JSON
。 - 为注释样式选择无。
- 单击“预览”按钮。
- 将生成的类复制并粘贴到您的项目中。
- 要自动解析
JSON
字符串,请使用以下代码:Example example = new Gson().fromJson(json, Example.class);
关于java - JSON 字符串的字符串扫描和 JSON 解析之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37642963/