英文:
Sort JSON objects by key in Java
问题
import java.util.*;
import org.json.*;
public class sample2 {
public static void main(String[] args) {
String jsonArrStr = "[ "
+ "{\"ID\": \"135\", \"Name\": \"Fargo Chan\" },"
+ "{\"ID\": \"432\", \"Name\": \"Aaron Luke\" },"
+ "{\"ID\": \"252\", \"Name\": \"Dilip Singh\" }]";
JSONArray jsonArr = new JSONArray(jsonArrStr);
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArr.length(); i++) {
jsonValues.add(jsonArr.getJSONObject(i));
}
Collections.sort(jsonValues, new Comparator<JSONObject>() {
// You can change "Name" with "ID" if you want to sort by ID
private static final String KEY_NAME = "Name";
@Override
public int compare(JSONObject a, JSONObject b) {
String valA = "";
String valB = "";
try {
valA = a.get(KEY_NAME).toString();
valB = b.get(KEY_NAME).toString();
} catch (JSONException e) {
// Handle the exception
}
return valA.compareTo(valB);
// If you want to change the sort order, simply use the following:
// return -valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArr.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
System.out.println(sortedJsonArray.toString());
}
}
英文:
I'm sorting JSON objects in a JSON array by passing the JSON key.
My program is working only when the json value is String
Example:- {"id":"0001"}
so whenever there is integer value program throws an error.
Example:- {"id":0001}
program:-
import java.util.*;
import org.json.*;
public class sample2 {
public static void main(String[] args) {
String jsonArrStr = "[ "
+ ""
+ "{ \"ID\": \"135\", \"Name\": \"Fargo Chan\" },"
+ "{ \"ID\": \"432\", \"Name\": \"Aaron Luke\" },"
+ "{ \"ID\": \"252\", \"Name\": \"Dilip Singh\" }]";
JSONArray jsonArr = new JSONArray(jsonArrStr);
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArr.length(); i++) {
jsonValues.add(jsonArr.getJSONObject(i));
}
Collections.sort(jsonValues, new Comparator<JSONObject>() {
// You can change "Name" with "ID" if you want to sort by ID
private static final String KEY_NAME = "Name";
@Override
public int compare(JSONObject a, JSONObject b) {
System.out.println("a " + a.toString());
System.out.println("b " + b.toString());
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_NAME);
System.out.println("valA " + valA);
valB = (String) b.get(KEY_NAME);
System.out.println("valB " + valB);
} catch (JSONException e) {
// do something
}
return valA.compareTo(valB);
// if you want to change the sort order, simply use the following:
// return -valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArr.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
System.out.println(sortedJsonArray.toString());
}
}
How to make above program work dynamically for all the DATA-TYPES(String,Integer,Float,Double).
答案1
得分: 0
有不多的方法来实现你想要达到的目标。虽然有反射 API,但它带有许多缺点,不太可靠和直接。然而,最可靠且简单的方法是使用 instanceof
运算符。
通过这种方法,你可以完全控制每个转换和比较,还可以使用实现了 compareTo()
方法的自定义类进行比较。除非你有太多可能性需要涵盖,这可能是最佳方法。
我假设你知道 JSONObject.get() 方法会将对象转换为 Object 类型,因此可以添加如下条件:
Object obj1 = a.get(KEY_NAME);
Object obj2 = b.get(KEY_NAME);
if (obj1 instanceof Integer && obj2 instanceof Integer) {
return ((Integer) obj1).compareTo(((Integer) obj2));
} else if (obj1 instanceof Double && obj2 instanceof Double) {
return ((Double) obj1).compareTo(((Double) obj2));
} else if (obj1 instanceof Double || obj2 instanceof Double) {
Double v1 = ((Number) obj1).doubleValue();
Double v2 = ((Number) obj2).doubleValue();
return v1.compareTo(v2);
}
由于 Number 类是
Integer
、Float
和Double
的超类,所以你可以从那里进行转换。
这可能会引入很多代码,但会增加可靠性,遇到意外的 JSON 时也不会有意外情况。此外,额外的条件将能够处理不匹配的数据类型,还可以检测 JSON 对象中的错误。
英文:
There are not many ways to to what you want to achieve. Refelection API is there but it comes with many drawbacks and not very reliable and straightforward. However, the most reliable and easy way is to use instanceof
operator.
With this method you have full control over every conversion and comparison, also you can compare custom classes with compareTo() method implemented. Unless you have too many possibilities to cover, this maybe the best approach.
I assume that you know that JSONObject.get() method converts object into Object types so add conditions like
Object obj1 = a.get(KEY_NAME);
Object obj2 = b.get(KEY_NAME);
if(obj1 instanceof Integer && obj2 instanceof Integer){
return ((Integer) obj1).compareTo(((Integer) obj2));
} else if(obj1 instanceof Double && obj2 instanceof Double){
return ((Double) obj1).compareTo(((Double) obj2));
} else if(obj1 instanceof Double || obj2 instanceof Double){
Double v1 = ((Number) obj1).doubleValue();
Double v2 = ((Number) obj2).doubleValue();
return v1.compareTo(v2);
}
> As Number class is super class of Integer
, Float
and Double
, so you
> can convert it from there.
It may induce lot of code but will add reliability but no surprises when unexpexcted JSON is encountered. Also additional conditions would be able handle to handle mismatching data types and and could also detect error in JSON object.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论