如何使用 Java 从 JSONArray 中删除重复和排序对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32371236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove duplicate and sort objects from JSONArray using Java
提问by Govind Mantri
My JSON is:
我的 JSON 是:
[
{
"distance":32,
"stationCode":"MIG",
"name":"Midghat",
"platforms":"2"
},
{
"distance":32,
"stationCode":"MIG",
"name":"Midghat",
"platforms":"2"
},
{
"distance":69,
"stationCode":"MDDP",
"name":"Mandideep",
"platforms":"2"
},
{
"distance":69,
"stationCode":"MDDP",
"name":"Mandideep",
"platforms":"2"
},
{
"distance":18,
"stationCode":"HBD",
"name":"Hoshangabad",
"platforms":"2"
},
{
"distance":18,
"stationCode":"HBD",
"name":"Hoshangabad",
"platforms":"2"
},
{
"distance":37,
"stationCode":"CHQ",
"name":"Choka",
"platforms":"2"
},
{
"distance":37,
"stationCode":"CHQ",
"name":"Choka",
"platforms":"2"
},
{
"distance":85,
"stationCode":"HBJ",
"name":"Habibganj",
"platforms":"5"
},
{
"distance":85,
"stationCode":"HBJ",
"name":"Habibganj",
"platforms":"5"
},
{
"distance":0,
"stationCode":"ET",
"name":"ItarsiJn",
"platforms":"28"
},
{
"distance":8,
"stationCode":"PRKD",
"name":"Powerkheda",
"platforms":"2"
},
{
"distance":8,
"stationCode":"PRKD",
"name":"Powerkheda",
"platforms":"2"
},
{
"distance":55,
"stationCode":"ODG",
"name":"ObaidullaGanj",
"platforms":"2"
},
{
"distance":55,
"stationCode":"ODG",
"name":"ObaidullaGanj",
"platforms":"2"
},
{
"distance":44,
"stationCode":"BKA",
"name":"Barkhera",
"platforms":"2"
},
{
"distance":44,
"stationCode":"BKA",
"name":"Barkhera",
"platforms":"2"
},
{
"distance":79,
"stationCode":"MSO",
"name":"Misrod",
"platforms":"2"
},
{
"distance":79,
"stationCode":"MSO",
"name":"Misrod",
"platforms":"2"
},
{
"distance":25,
"stationCode":"BNI",
"name":"Budni",
"platforms":"2"
},
{
"distance":25,
"stationCode":"BNI",
"name":"Budni",
"platforms":"2"
},
{
"distance":91,
"stationCode":"BPL",
"name":"BhopalJn",
"platforms":"6"
},
{
"distance":63,
"stationCode":"ITKL",
"name":"ItayaKalan",
"platforms":"2"
},
{
"distance":63,
"stationCode":"ITKL",
"name":"ItayaKalan",
"platforms":"2"
}
]
I want it to sort according to distance and remove duplicate stationCode. I tried using simple if else but that process will be too much.. any shortcut for same specially for sorting.
我希望它根据距离进行排序并删除重复的 stationCode。我尝试使用简单的 if else 但这个过程会太多..任何专门用于排序的快捷方式。
采纳答案by nafas
I wrote this utility a while ago, it sorts a JSONArray
of JSONObjects
Only condition is that your JSONobjects
must contain the keys
you want to sort
based on (it also accept a set of keys if you want to sort based on several keys)
我前一段时间写了这个实用程序,它排序JSONArray
的JSONObjects
唯一条件是你JSONobjects
必须包含keys
你想要sort
基于的(如果你想基于多个键排序,它也接受一组键)
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JSONArraySort {
@SuppressWarnings("unchecked")
public static void sortASCE(JSONArray array, Object key) {
Object[] keys = { key };
Collections.sort(array, new JSONArrayComparator(false, keys));
}
@SuppressWarnings("unchecked")
public static void sortDESC(JSONArray array, Object key) {
Object[] keys = { key };
Collections.sort(array, new JSONArrayComparator(true, keys));
}
@SuppressWarnings("unchecked")
public static void sortASCE(JSONArray array, Object[] key) {
Collections.sort(array, new JSONArrayComparator(false, key));
}
@SuppressWarnings("unchecked")
public static void sortDESC(JSONArray array, Object[] key) {
Collections.sort(array, new JSONArrayComparator(true, key));
}
private static class JSONArrayComparator implements Comparator<JSONObject> {
private final Object[] KEYS;
private final boolean DESC;
public JSONArrayComparator(boolean DESC, Object[] KEYS) {
this.KEYS = KEYS;
this.DESC = DESC;
}
@Override
public int compare(JSONObject object1, JSONObject object2) {
int length = KEYS.length;
for(int i = 0 ; i < length ; i++){
String KEY = KEYS[i].toString();
Object one = object1.get(KEY);
Object two = object2.get(KEY);
if(Number.class.isAssignableFrom(one.getClass()) && Number.class.isAssignableFrom(two.getClass())){
Double numOne = Number.class.cast(one).doubleValue();
Double numTwo = Number.class.cast(two).doubleValue();
int compared = 0;
if(DESC){
compared = numTwo.compareTo(numOne);
}else{
compared = numOne.compareTo(numTwo);
}
if(i == KEYS.length - 1 || compared != 0){
return compared;
}
}else{
int compared = 0;
if(DESC){
compared = two.toString().compareTo(one.toString());
}else{
compared = one.toString().compareTo(two.toString());
}
if(i == KEYS.length - 1 || compared != 0){
return compared;
}
}
}
// this shouldn't happen.
return 0;
}
}
//testing...
public static void main(String... args) {
JSONArray array1 = new JSONArray();
for(int i = 0 ; i < 100 ; i++){
Random random = new Random();
int num1 = random.nextInt(10);
int num2 = random.nextInt(10);
JSONObject object = new JSONObject();
object.put("num1", num1);
object.put("num2", num2);
array1.add(object);
}
String[] keys = { "num1", "num2" };
sortASCE(array1, keys);
System.out.println(array1.toString());
}
}
now if you want to remove duplicates you can iterate
through them
现在如果你想删除重复项,你可以iterate
通过它们
Set<String> stationCodes=new HashSet<String>();
JSONArray tempArray=new JSONArray();
for(int i=0;i<yourJSONArray.size();i++){
String stationCode=yourJSONArray.getJSONObject(i).getString("stationCode");
if(stationsCodes.contains(stationCode){
continue;
}
else{
stationsCodes.add(stationCode);
tempArray.add(yourJSONArray.getJSONObject(i));
}
}
yourJSONArray= tempArray; //assign temp to original
//here how you can sort it using utility above:
JSONArraySort.sortASCE(yourJSONArray,"distance");
回答by Md. Kamruzzaman
There is no direct way to that but you can follow the way mentioned bellow:
没有直接的方法,但您可以按照下面提到的方法进行操作:
Transform JsonObject to Java Object list using org.codehaus.Hymanson.map.ObjectMapper
Use a Java Map to make unique (put key = stationCode, javaObject as object)
Sort the map data based on distance.
使用 org.codehaus.Hymanson.map.ObjectMapper 将 JsonObject 转换为 Java 对象列表
使用 Java Map 使其唯一(将 key = stationCode, javaObject 作为对象)
根据距离对地图数据进行排序。
回答by KodandaRamu Kodaconti
Here is the code for joining '2' JSONArrays and removing duplicates from the joined JSONArray, using ArrayList<String>..contains() method:
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author RAM K K
* @gmail [email protected]
*
*/
public class JSONOperations {
public static void main(String[] args) {
String s3;
String s1 = "[{\"name\": \"Bob\", \"car\": \"Ford\"},{\"name\": \"Steve\", \"car\": \"Mercedes Benz\"},{\"name\": \"Bob\", \"car\": \"Ford\"},{\"name\": \"Bob\", \"car\": \"Ford\"},{\"name\": \"Bob\", \"car\": \"Ford\"},{\"name\": \"Bob\", \"car\": \"Ford\"},{\"name\": \"Mary\", \"car\": \"Fiat\"}]";
String s2 = "[{\"name\": \"Mack\", \"car\": \"VW\"},{\"name\": \"Steve\", \"car\": \"Mercedes Benz\"},{\"name\": \"Bob\", \"car\": \"Ford\"}]";
try {
JSONArray sourceArray = new JSONArray(s2);
JSONArray destinationArray = new JSONArray(s1);
System.out.println(sourceArray);
System.out.println(destinationArray);
for (int i = 0; i < sourceArray.length(); i++) {
destinationArray.put(sourceArray.getJSONObject(i));
}
System.out.println(destinationArray);
System.out.println("JSONArray Size is: " + destinationArray.length());
List<String> list = new ArrayList<String>();
for (int i = 0; i < destinationArray.length(); i++) {
if (!list.contains(destinationArray.get(i).toString())) {
list.add(destinationArray.get(i).toString());
}
}
System.out.println("LIST: " + list);
System.out.println("LIST Size: " + list.size());
JSONArray distinctJSONArray = new JSONArray(list.toString());
System.out.println(distinctJSONArray.length());
for (int i = 0; i < distinctJSONArray.length(); i++) {
JSONObject JSON = (JSONObject) distinctJSONArray.getJSONObject(i);
System.out.println(JSON);
}
s1 = s1.substring(s1.indexOf("[") + 1, s1.lastIndexOf("]"));
s2 = s2.substring(s2.indexOf("[") + 1, s2.lastIndexOf("]"));
s3 = "[" + s1 + "," + s2 + "]";
System.out.println(new JSONArray(s3));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}