私はJSON
次のような応答があるアプリケーションを開発しています。
{
"notifications":{
"0":{
"text":"First One",
"state":"new"
},
"1":{
"text":"Second One",
"state":"new"
},
"2":{
"text":"Third One",
"state":"new"
},
"3":{
"text":"Fourth One",
"state":"old"
},
"4":{
"text":"Fifith One",
"state":"old"
}
}
}
クラスを使用してIterator
この応答を解析しています。私はこのようなことをしています:
notifyList = new ArrayList<HashMap<String, String>>();
try {
JSONObject rootObj = new JSONObject(result);
JSONObject jSearchData = rootObj.getJSONObject("notifications");
Iterator<String> keys = jSearchData.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject jNotification0 = jSearchData.optJSONObject(key);
if (jNotification0 != null) {
String text = jNotification0.getString("text");
String state = jNotification0.getString("state");
HashMap<String, String> map = new HashMap<String, String>();
map.put("text", text);
map.put("state", state);
System.out.println("Text: " + text);
System.out.println("State: " + state);
notifyList.add(map);
}
else {
}
JSON
しかし、これはごちゃごちゃした形式のデータを提供します。それは、応答のように賢明ではありません。
以下は、log
すべてがごちゃ混ぜになっている which の出力です。
Text: Fourth One
State: old
Text: Third One
State: new
Text: Second One
State: new
Text: First One
State: new
Text: Fifth One
State: old
「状態」変数を使用し、それに応じてソートして、「新しい」状態が「古い状態」の前に最初に来るようにしました。しかし、応答に 2 ~ 3 個の新しい状態がある場合、これは役に立ちません。
私は次のようなコレクションコードを試しました:
Collections.sort(notifyList,
new Comparator<Map<String, String>>() {
@Override
public int compare(final Map<String, String> map1,
final Map<String, String> map2) {
int comparison = map1.get("state")
.compareToIgnoreCase(map2.get("state"));
if (comparison == 0)
return 0;
else if (comparison > 0)
return 1;
else
return -1;
}
}
);
この問題を解決する方法はありますか?
あらゆる種類の助けをいただければ幸いです。