解析 json 对象后,按时间顺序对 json 对象进行排序



这是代码: 我想根据时间和/或日期对它们进行排序: 它们已经显示,只是没有按顺序显示。现在,我拥有的是将 json 对象解析为 xml 的代码。我想做的只是根据时间和/或日期解析它们。下面的项目是JSON文件的示例,其中有不同的日期和时间(2分钟前,5分钟前等(

try {
// Create the root JSONObject from the JSON string.
JSONObject jsonRootObject = new JSONObject(myjsonstring);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.getJSONArray("Postdetails");
//Iterate the jsonArray and print the info of JSONObjects
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//Collections.sort(jsonValues);
String text = jsonObject.optString("number_of_likes").toString();
String minute = jsonObject.optString("min_ago").toString();
//float salary = Float.parseFloat(jsonObject.optString("salary").toString());
time += minute + "n" + "n" + "n" + "n" + "n" + "n" + "n";
data += text;
}
output.setText(data);
timeago.setText(time);

} catch (JSONException e) {
e.printStackTrace();
}

JSON 文件:

{
"Postdetails": [
{
"min_ago": "2 min ago",
"number_of_likes": "63",
"number_of_comments": "92",
"date": "7 March 2017"
},
{
"min_ago": "5 min ago",
"number_of_likes": "72",
"number_of_comments": "123",
"date": "7 March 2017"
},
{
"min_ago": "9 min ago",
"number_of_likes": "123",
"number_of_comments": "9123",
"date": "10 March 2017"
},
{
"min_ago": "6 min ago",
"number_of_likes": "133",
"number_of_comments": "9123",
"date": "9 March 2017"
}
]
}

当您提取日期以对它们进行排序时,您已经解析了它。对于您的应用程序(或不知道您的用例(可能有意义的是在第一次解析后缓存结果,可能是通过使用某种数据库,但如果您的数据结构像这样简单,甚至可能有点矫枉过正。

如果你想遵循缓存策略,你可以使用像SQLite这样的数据库(使用它上面的Room来使访问更容易,或者其他一些ORM(,或者Realm,它有很多在线教程。还有更多,但这两个是我觉得更容易使用的。

最新更新