進口?Java . lang . reflect . type;
進口?Java . util . *;
進口?com . Google . gson . gson;
進口?com . Google . gson . reflect . type token;
公共的?上課?占蔔?{
公共的?靜電?虛空?main(String【】?args)?{
字符串?jsonStr?=?“【{ \“depid \“:\“5 \“,\“score \“:\“10 \“},{ \“depid \“:\“4 \“,\“score \“:\“40 \“},{ \“depid \“:\“4 \“,\“score \“:\“30 \“},{ \“depid \:\“5 \“,\“score \:\“30 \“}“;
System.out.println(“原始json字符串:“?+?jsonStr);
//?分析
Gson?gson?=?新的?gson();
類型?類型?=?新的?TypeToken & lt數組列表& ltJsonData & gt& gt()?{
}.getType();
數組列表& ltJsonData & gt?名單?=?gson . from JSON(jsonStr,?類型);
//?合並
列表& ltJsonData & gt?訂購的?=?新的?數組列表& lt& gt();
地圖& lt整數,?JsonData & gt?地圖?=?新的?HashMap & lt& gt();
為了什麽?(JsonData?jsonData?:?列表)?{
JsonData?數據?=?map . get(JSON data . get depid());
如果?(數據?!=?null)?{?//?合並具有相同depid的分數字段
data . set score(data . get score()?+?JSON data . get score());
}?不然呢?{
map . put(JSON data . get depid(),?JSON data);
ordered . add(JSON data);
}
}
//?還原到json字符串
System.out.println(“合並的json字符串:“?+?gson . toj son(map . values()));
System.out.println(“合並的json字符串(按原始順序)”:“?+?gson.toJson(有序));
}
}
上課?JsonData?{
私人的?int?德比德;
私人的?int?得分;
公共的?int?getDepid()?{
回歸?德比德;
}
公共的?虛空?setDepid(int?depid)?{
這個,戴普?=?德比德;
}
公共的?int?getScore()?{
回歸?得分;
}
公共的?虛空?setScore(int?得分)?{
這個。得分?=?得分;
}
}列表
運行結果: