Seeker
Seeker

Reputation: 1927

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 w.r.t the value lineNumber. lineNumber array always has only one element inside. I am using simple JSON.

Upvotes: 1

Views: 426

Answers (1)

Janez Kuhar
Janez Kuhar

Reputation: 4286

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 Values, or in your case JSONObjects. The easiest way to do this is to write a custom Comparator and sort your list via Collections.sort(...).

Upvotes: 0

Related Questions