0

Keys from Map are printed as [index].keyname. How to get the index value from keys?

Code:

Map<String, Object> flattenedJsonMap = JsonFlattener.flattenAsMap(response.readEntity(String.class));

Map<String,Object> keysMap = new HashMap<>();
flattenedJsonMap.forEach(
       (k, v) -> keysMap.put(k, v)
);

for (String kval : keysMap.keySet()) {
    if (kval.contains("paper_id")) {
           System.out.println("\nkval="+kval+"\n"+keysMap.get(kval));
    }
}

Sample output

kval=[3].paper_id
01e3b313e78a352593be2ff64927192af66619b5

kval=[1].paper_id
004f0f8bb66cf446678dc13cf2701feec4f36d76

kval=[2].paper_id
01d162d7fae6aaba8e6e60e563ef4c2fca7b0e18

Wanted to get the total or get the index values (1,2,3 etc) from key ([1].paper_id)

Suren Konathala
  • 3,497
  • 5
  • 43
  • 73
  • Just to clarify, the input JSON was a a list of objects each of which has a paper_id property? Is that the whole of the JSON or is that just a sub-part? Basically what is the actual input and desired output? If the input is as simple as that I'm just wondering if JsonFlattener is the best tool for the job. – Chris Mar 30 '20 at 19:37
  • Especially if you want the indexes in order - adding to a map will lose the ordering, unless you stick them in a TreeMap, but alternatively if you just deserialize into a List then you could just go through a list incrementing an index as you go (unless you use Kotlin then you can use one of the handy methods like mapIndexed) – Chris Mar 30 '20 at 19:48
  • The json is complex and nested, i'm trying to simplify it and map it to an object. – Suren Konathala Mar 30 '20 at 20:23
  • Hi Suren, I think adding the input (or part of it if it is huge) and desired output would really clarify the question, I'm still not quite sure what you are aiming for - for example when you say map it to an object then I'd think of ObjectMapper straight away as a solution. – Chris Mar 30 '20 at 20:30

0 Answers0