0

There is a very nice KeyFinder example on the json-simple docs

But if I try to get an array, it will only return me the first element json

{"foo": 
    {"bar": 
        {"foobar":{
        "items":["item1","item2","item3"]
                }
        }
    }
}

If I use the example of keyFinder and search for "items", I only get "item1" whereas I want to be able to use the whole array.

Example of what the keyFinder does / how it is working:

KeyFinder finder = new KeyFinder();
finder.setMatchKey("items"); 
try{
   while(!finder.isEnd()){
      if(finder.isFound)
        System.out.println("finder.getValue() -->" + finder.getValue()
    }
}//...

How I do currently:

    Object obj = parser.parse(jsonText);
    JSONObject jsonObject = (JSONObject) obj;
    JSONObject jsonTags = (JSONObject) ((JSONObject) ((JSONObject) jsonObject.get("foo")).get("bar")).get("foobar");
    String tags = (String) jsonTags.get("items").toString().replaceAll("[^A-Za-z0-9,]","");
    String[] vaca = tags.split(",");
    for(String s : vaca) {
        list.add(s);
        System.out.println(s);
    }

My question is how to get the array without knowing the "path" foo >> bar >> foobar to get the "items" array by its key.

DeMarco
  • 599
  • 1
  • 8
  • 26

1 Answers1

0

It will give you full array. One mistake you were making is you didn't wrapped foo, bar and foobar in "". It should be like this :

{"foo": 
    {"bar": 
        {"foobar":{
        "items":["item1","item2","item3"]
                }
        }
    }
}

I tried your code

JSONParser parser = new JSONParser();
Object obj = parser.parse(jsonText);
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonTags = (JSONObject) ((JSONObject) ((JSONObject) jsonObject.get("foo")).get("bar")).get("foobar");
String tags = (String) jsonTags.get("items").toString().replaceAll("[^A-Za-z0-9,]","");
String[] vaca = tags.split(",");
List<String> list = new ArrayList<>();
for(String s : vaca) {
    list.add(s);
    System.out.println(s);
}

And the output is :

item1
item2
item3
afzalex
  • 8,598
  • 2
  • 34
  • 61
  • While I agree that the json on my question is wrong. I made it to illustrate the problem. My question is how to get the items array without knowing that in order to get there I must go through foo>> bar>> foobar>> Sorry if the question isn't clear. – DeMarco Feb 18 '16 at 11:58