2017-08-27 404 views
-2

这里是代码: 我想根据时间和/或日期对它们进行排序: 它们已经被显示,只是不按顺序显示。现在,我所拥有的是将json对象解析为xml的代码。我想要做的就是根据时间和/或日期来解析它们。下面的产品,其中有不同的日期和时间(2分钟前,5分钟前等)根据时间对json对象进行排序解析后的顺序

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文件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" 
    } 
    ] 
} 
+0

当你提取日期来订购它们时,你已经解析了它。对你的应用程序有意义(或不知道你的用例)是在第一次解析之后缓存结果,可能是使用某种数据库,但如果你的数据结构如此简单,甚至可能会过度作为这一个。 –

+0

如何缓存结果? –

+0

移动我的问题答案,见下文。 –

回答

0

到时候你提取日期要订购它们,你已经解析了它。对你的应用程序有意义(或不知道你的用例)是在第一次解析之后缓存结果,可能是使用某种数据库,但如果你的数据结构如此简单,甚至可能会过度作为这一个。

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

相关问题