2017-08-27 54 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,它有大量的在線教程。還有更多,但這兩個是我覺得更容易使用的。

相關問題