0

Hi, how I can retrieve information from my Json file to a list. And check the information in the list

Please note that the number of servers may increase

My Json file

{
  "servers": {
    "server1": {
      "name": "Name1",
      "allowStart": true,
      "realIP": "0.0.0.0"
    },
    "server2": {
      "name": "Name2",
      "allowStart": false,
      "realIP": "0.0.0.0"
    },
    "server3": {
      "name": "Name3",
      "allowStart": true,
      "realIP": "0.0.0.0"
    }
  }
}

i want to get something like this:


String serverip = "0.0.0.0";

/* code for get ListServer.name ListServer.allowStart ListServer.realIP */

if (ListServer.realIP == serverip && ListServer.allowStart == true){

    System.out.print(ListServer.name + " allow to start? " + ListServer.allowStart);


}

Ideally it would be good to recover this json file from a site.

Help me please.

  • Does this answer your question? [How to parse JSON in Java](https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – denvercoder9 Jun 02 '20 at 15:15
  • `ListServer.realIP == serverip` [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – denvercoder9 Jun 02 '20 at 15:17

2 Answers2

1

Unless you want to write your own parser, you can just easily add the JSON package from org.json. Either download it or just add it as a dependency. It's fairly straight forward to use and there is a good reference here: https://www.baeldung.com/java-org-json

as for recovering the json from a (I'm assuming external) site you could write something like this:


import java.net.*;
import java.io.*;

URL yourJson = new URL(<your ip here>);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(
      new InputStreamReader(new InputStreamReader(
                yourJson.openStream()), "UTF-8"));


1

Your json file contains three separate server objects within the servers node. They are not in the form of a jsonArray. However, You can try something like this with Gson dependency. Then you can map them to a List separately or to a new object and store in a List

    Gson g = new Gson();

    LinkedTreeMap o = ( LinkedTreeMap ) g.fromJson( x, Object.class ); // x is the variable holding json variable
    LinkedTreeMap servers = ( LinkedTreeMap ) o.get( "servers" );
    LinkedTreeMap server1 = ( LinkedTreeMap ) servers.get( "server1" );

    // if needed iterate the key set, here I am only providing values of a single entry
    System.out.println( "serverName : " + server1.get( "name" ) );
    System.out.println( "allowStart : " + server1.get( "allowStart" ) );
    System.out.println( "realIP : " + server1.get( "realIP" ) );
Klaus
  • 1,641
  • 1
  • 10
  • 22