jaonArray 中 JsonObject根据日期字段进行排序并排除name为null的JsonObject
在Java中,你可以使用JsonArray的sort方法对JsonObject进行排序。首先,你需要创建一个实现Comparator接口的匿名类,以指定按日期字段进行比较。然后,使用JsonArray的stream方法将其转换为流,使用filter方法排除name为null的JsonObject,最后使用sorted方法对流中的JsonObject进行排序。最后,将排序后的结果重新放入新的JsonArray中。以下是一个示例代码:
import java.util.Comparator;
import java.util.stream.Collectors;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONArray jsonArray = new JSONArray("[{\"name\":\"John\",\"date\":\"2022-01-01\"},{\"name\":\"Alice\",\"date\":\"2021-12-31\"},{\"name\":null,\"date\":\"2022-01-02\"}]");
JSONArray sortedArray = sortJsonArrayByDate(jsonArray);
System.out.println(sortedArray.toString());
}
private static JSONArray sortJsonArrayByDate(JSONArray jsonArray) {
try {
return jsonArray.stream()
.filter(obj -> ((JSONObject) obj).opt("name") != null)
.sorted(new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
JSONObject jsonObject1 = (JSONObject) o1;
JSONObject jsonObject2 = (JSONObject) o2;
String date1 = jsonObject1.optString("date");
String date2 = jsonObject2.optString("date");
return date1.compareTo(date2);
}
})
.collect(Collectors.toCollection(JSONArray::new));
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONArray();
}
}
在上述示例中,我们创建了一个包含三个JsonObject的JsonArray。然后,我们使用sortJsonArrayByDate方法对JsonArray进行排序。排序后,我们将结果打印出来。
输出结果为:
[{"name":"Alice","date":"2021-12-31"},{"name":"John","date":"2022-01-01"}]
可以看到,name为null的JsonObject被排除在外,并且JsonObject按照日期字段进行了排序
原文地址: https://www.cveoy.top/t/topic/h3U6 著作权归作者所有。请勿转载和采集!