-2

I have a return from Web-Service like this :

Object result = envelope.getResponse();

AND the return is like this

[{"nom":"Nexus09","poste":"4319"},{"nom":"Nexus08","poste":"4312"},{"nom":"Nexus07","poste":"4306"}]

I need to foreach the result to get "nom" and "poste" for every {"nom":"Nexus09","poste":"4319"}

THX

Med Sniper
  • 43
  • 8
  • 4
    Possible duplicate of [How to iterate over a JSONObject?](https://stackoverflow.com/questions/9151619/how-to-iterate-over-a-jsonobject) – Orgil Nov 02 '18 at 08:12
  • Possible duplicate of [How can I access each key and value in JSONArray](https://stackoverflow.com/questions/29696713/how-can-i-access-each-key-and-value-in-jsonarray) – thestruggleisreal Nov 02 '18 at 08:39

2 Answers2

1

Using http://central.maven.org/maven2/org/json/json/20180813/json-20180813.jar Jar,

public static void main(String[] args) {
    String input="[{\"nom\":\"Nexus09\",\"poste\":\"4319\"},{\"nom\":\"Nexus08\",\"poste\":\"4312\"},{\"nom\":\"Nexus07\",\"poste\":\"4306\"}]";

    JSONArray jsonArray = new JSONArray(input); 

    jsonArray.forEach(j->System.out.println(j.toString()));     

}

To parse the nested JSONObject, It can be done like below,

public static void main(String[] args) {
    String input="[{\"nom\":\"Nexus09\",\"poste\":\"4319\"},{\"nom\":\"Nexus08\",\"poste\":\"4312\"},{\"nom\":\"Nexus07\",\"poste\":\"4306\"}]";

    JSONArray jsonArray = new JSONArray(input);         

    for(Object object:jsonArray) {
        if(object instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject)object;

            Set<String> keys =jsonObject.keySet();
            for(String key:keys) {
                System.out.println(key +" :: "+jsonObject.get(key));;
            }               
        }
    }

}
0

Here is the code to loop through an array of JSON and also get all key-value pairs. This should work.

Hope it helps.

Code:

Iterator<String> keys = json.keys();

while (keys.hasNext()) {
    String key = keys.next();
    System.out.println("Key :" + key + "  Value :" + json.get(key));
}
for(JSONObject json : result)
{
    Iterator<String> keys = json.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        System.out.println("Key :" + key + "  Value :" + json.get(key));
    }
}
Harshith Rai
  • 3,018
  • 7
  • 22
  • 35