按键在Java中对JSON对象进行排序

huangapple go评论77阅读模式
英文:

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:- {&quot;id&quot;:&quot;0001&quot;}

so whenever there is integer value program throws an error.

Example:- {&quot;id&quot;:0001}

program:-

import java.util.*;
import org.json.*;
public class sample2 {
public static void main(String[] args) {
String jsonArrStr = &quot;[ &quot;
+ &quot;&quot;
+ &quot;{ \&quot;ID\&quot;: \&quot;135\&quot;, \&quot;Name\&quot;: \&quot;Fargo Chan\&quot; },&quot;
+ &quot;{ \&quot;ID\&quot;: \&quot;432\&quot;, \&quot;Name\&quot;: \&quot;Aaron Luke\&quot; },&quot;
+ &quot;{ \&quot;ID\&quot;: \&quot;252\&quot;, \&quot;Name\&quot;: \&quot;Dilip Singh\&quot; }]&quot;;
JSONArray jsonArr = new JSONArray(jsonArrStr);
JSONArray sortedJsonArray = new JSONArray();
List&lt;JSONObject&gt; jsonValues = new ArrayList&lt;JSONObject&gt;();
for (int i = 0; i &lt; jsonArr.length(); i++) {
jsonValues.add(jsonArr.getJSONObject(i));
}
Collections.sort(jsonValues, new Comparator&lt;JSONObject&gt;() {
// You can change &quot;Name&quot; with &quot;ID&quot; if you want to sort by ID
private static final String KEY_NAME = &quot;Name&quot;;
@Override
public int compare(JSONObject a, JSONObject b) {
System.out.println(&quot;a &quot; + a.toString());
System.out.println(&quot;b &quot; + b.toString());
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_NAME);
System.out.println(&quot;valA &quot; + valA);
valB = (String) b.get(KEY_NAME);
System.out.println(&quot;valB &quot; + 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 &lt; 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 类是 IntegerFloatDouble 的超类,所以你可以从那里进行转换。

这可能会引入很多代码,但会增加可靠性,遇到意外的 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 &amp;&amp; obj2 instanceof Integer){
return  ((Integer) obj1).compareTo(((Integer) obj2));
} else if(obj1 instanceof Double &amp;&amp; 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.

huangapple
  • 本文由 发表于 2020年10月9日 01:11:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64267483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定