-1

I need to get the ID of room by its name from JSONObject.

I uploaded Json file here: https://gitlab.com/JaroslavVond/json/blob/master/Json

So I know the name of the room (Kitchen1) and I need to write some function in Java that will return me the ID of the room (in this case "1").

Any ideas how to do that?

So far I have something like this:

private static String GetIdRoom(String room) {

    String id = "";
    JSONObject myResponse = SendHTTP("/groups", "GET", "");

    try {

      // some code to get ID of room            

    } catch (Exception ex) {
        System.out.println("error - " + ex);
    }

    return null ;

}
KoRaP CZ
  • 53
  • 6
  • 1
    First you need some JSON library and because each one is slightly different, the answer will depend on the library you are using. So which library are you using? – Abra Oct 26 '19 at 16:10
  • I am using this library: https://jar-download.com/artifacts/org.json – KoRaP CZ Oct 26 '19 at 16:13
  • https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java – JGFMK Oct 26 '19 at 16:15
  • Have you tried anything? The ID is one of the keys of your object. This key is associated to the value which is another object with a name attribute. So you could iteratre through the entries, check is the value of the entry is an object with the searched name attribute, and if it is, return the key of the entry. To do that, you need to learn about the API of the library that you're using. Where is its documentation? Have you read it? – JB Nizet Oct 26 '19 at 16:28
  • @JBNizet thats right... its a key... so I just used `myResponse.keys()` and then checked names. So easy. Thank you. – KoRaP CZ Oct 26 '19 at 17:29

1 Answers1

1
Iterator<?> ids = myResponse.keys();

        while( ids.hasNext() ) {

             id = (String) ids.next();

            if(myResponse.getJSONObject(id).getString("name").equals(room)){
                return id;
            }
        }
KoRaP CZ
  • 53
  • 6
  • Well done! :-) The API is your friend. A good java programmer knows how to use it in order to help him get the job done. – Abra Oct 26 '19 at 18:05