0

I have the following JSONObject

{"results":2,"object":[{"id":10,"rank":12},{"id":21,"rank":22}.........{"id":n,"rank":n}]}

Now if I have an id: 21, how do I get the position of that object?

Is there any direct way to get the position of that id?

Like 21 is in 2nd position in that array.So the index position is 1. Is there any direct way without looping the JSONArray to improve the performance?

gprathour
  • 14,813
  • 5
  • 66
  • 90
user3750720
  • 163
  • 1
  • 13
  • Sorry thats by mistake. Corrected in the question @Ramanlfc – user3750720 Aug 21 '17 at 04:31
  • 2
    Since you have JSON objects inside your JSON array, I don't see any way you can access the keys inside directly. – Debanik Dawn Aug 21 '17 at 04:36
  • 1
    No, but parsing the JSON in the first place is probably much more costly. Why do you think performance is an issue here? – shmosel Aug 21 '17 at 04:39
  • Use Map to store id as key and related attributes as values. – Vinujan.S Aug 21 '17 at 04:43
  • 1
    You might get some help here: https://stackoverflow.com/questions/777455/is-there-a-query-language-for-json . But, the question is do you really have that complex require or just some filtering will do. – Kislay Kishore Aug 21 '17 at 04:43
  • @KislayKishore i wouldn't say its complex but there are about 6000 calls that will happen and that needs to get the position. If we loop it, it takes a lot of time. So just trying to reduce the time taking here. – user3750720 Aug 21 '17 at 04:57
  • 1
    Perhaps, perhaps stream based parsing ( GSON or similar) could be an option for determining the index? (https://sites.google.com/site/gson/streaming) – Kislay Kishore Aug 21 '17 at 05:05

1 Answers1

0

One thing you can do is to re-structure your json like

{"results":2,"object":{10:{"pos":1,"rank":12},21:{"pos":2,"rank":22}.........n:{"pos":n,"rank":n}}}

Then you can directly fetch it using object[ur_id].pos

Girish007
  • 442
  • 6
  • 26