简体   繁体   中英

Sorting JSONObject using a value of a JSONArray in Java

I have following JSONObject i am trying to sort:

{
  "coords": {
    "27": {
      "x": [70,71,72],
      "y": [1945,1946,1947],
      "lineNumber": [
        19
      ]
    },
    "29": {
      "x": [70,71,72],
      "y": [1945,1946,1947],
      "lineNumber": [
        91
      ]
    },
    "2333": {
      "x": [70,71,72],
      "y": [1945,1946,1947],
      "lineNumber": [
        10
      ]
    }
  }
}

I wanted to sort the JSONObjects inside coords wrt the value lineNumber . lineNumber array always has only one element inside. I am using simple JSON.

Unfortunately there isn't a clean way to do this.

You can convert your map to a list of Map.Entry<K,V> objects. In your case the entries are of type Map.Entry<String, JSONObject> (entries inside coords ).

The list can then be sorted by entry V alues, or in your case JSONObject s. The easiest way to do this is to write a custom Comparator and sort your list via Collections.sort(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM