2016-11-09 9 views
0

その日付フィールドYYYY-MM-DDでJSONArray文字列のソートHH-MM-SS.SSS

[{"2016-11-09 19:01:59.649":"[email protected]::example message"}, 
{"2016-11-09 19:01:05.542":"[email protected]::another example"}, 
{"2016-11-09 19:02:01.394":"[email protected]::another one"}] 

は、すべて並べ替えるためにいくつかの効率的な方法はありますJSONオブジェクトは時系列で表示されますか?

+1

私は 'JSONObject'でキーとして日付フィールドを保つことがなかったです。私はそれがあなたがこれをどのように使用しようとしているかを混乱させると思う。 –

+0

@Andrew:ソートするオブジェクトの数はいくつですか? – walkeros

+0

@walkerosは最大200個のオブジェクトで、それ以上のものではありません – Andrew

答えて

0

あなたは、あなたがあなたのJSONObjectインスタンスで唯一のエントリを持っていることをしたと仮定すると:

  1. ソート
  2. JSONArrayからJSONObject秒の最初のキーを比較してJSONObjectの配列をJSONObjectインスタンスを抽出、
  3. 新しいJSONArrayを作成するか、古いJSONArrayに値を再設定します。このよう

何か:

// Build the source JSONArray 
JSONArray array = new JSONArray(); 
array.put(
    new JSONObject("{\"2016-11-09 19:01:59.649\":\"[email protected]::example message\"}") 
); 
array.put(
    new JSONObject("{\"2016-11-09 19:01:05.542\":\"[email protected]::another example\"}") 
); 
array.put(
    new JSONObject("{\"2016-11-09 19:02:01.394\":\"[email protected]::another one\"}") 
); 

// Extract the JSONObjects 
JSONObject[] objects = new JSONObject[array.length()]; 
for (int i = 0; i < objects.length; i++) { 
    objects[i] = array.getJSONObject(i); 
} 
// Sort the array of JSONObjects 
Arrays.sort(
    objects, 
    (JSONObject o1, JSONObject o2) -> 
     ((String)o1.keys().next()).compareTo((String)o2.keys().next()) 
); 
// Build a new JSONArray from the sorted array 
JSONArray array2 = new JSONArray(); 
for (JSONObject o : objects) { 
    array2.put(o); 
} 
System.out.println(array2); 

出力:

[{"2016-11-09 19:01:05.542":"[email protected]::another example"},{"2016-11-09 19:01:59.649":"[email protected]::example message"},{"2016-11-09 19:02:01.394":"[email protected]::another one"}] 
+1

ありがとう、それはかなり良いですね!私はしばらくのうちにそれを試して、それが機能するとすぐに正しい答えとしてそれを受け入れます。 – Andrew

関連する問題