-1

I have a string in below format and would want to access certain elements from it such as host/username.

{
 "username":"admin",
 "password":"admin1234",
 "engine":"mysql",
 "host":"toolsdata.us-east-1.rds.amazonaws.com",
 "port":3306,
 "dbname":"tools_data",
 "dbInstanceIdentifier":"toolsdata
}

I tried using List<String> or String[] to retrieve values, but unable to do so.

Is there another way I can get the each element from above string?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

1

You can use org.json.JSONObject (https://mvnrepository.com/artifact/org.json/json) class in order to access key-value features.

To create JSONObject just pass JSON value as string to its constructor:

String jsonAsString = "Your JSON as string...";
JSONObject json = new JSONObject(jsonAsString);

And now you can easily access value by given key:

json.getString("username");
json.getInt("port");

You can learn more about different JSON parsing approaches in this tutorial: How to Parse JSON in Java

Lukasz Blasiak
  • 642
  • 2
  • 10
  • 16
1

A String containing JSON is just a string. It will not magically be parsed into anything else. Not split into lines, not interpreted as Json, nothing. And how would it, Java doesn't know about its contents or what meaning it has to you.

So, to be able to process the JSON, you have to write code that tokenizes and parses the JSON into Objects that provide the necessary functions to access its keys and values.

There is multiple libraries that prvide those capabilities. Amongst the most capable and well known ones are Jackson and GSON, but they might be an overkill for a task as simple as yours. A simpler library like JSONObject might suffice.

The main difference is: JSON serializeation / deserialization libraries like Jackson or GSON parse known Json into user-defined objects. If the fields in JSON and in your Java object don't match, it won't work. But IF they do, you have type-safe access to all the keys and can use your Object like any regular Java object. Libraries like JSONObject work differnetly: They don't need to know anything about your JSON Objects, they parse it into Wrapper objects that you can then query for data. They can work with any valid JSON input, but if you make assumptions about which keys are present and which type they have, and those assumptions do not hold true, you can errors when accessing them. So, no type-safety here.

Code below does NOT account for potential exceptions thrown by any of the libraries and noes not include any null-checks either.

Jackson:

class Settings {
    String username;
    String password;
    String engine;
    String host;
    Integer port;
    String dbname;
    String dbInstanceIdentifier;

    public static Settings fromJson (String jsonData) {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(jsonData, Settings.class);
    }
}

GSON

class Settings {
    String username;
    String password;
    String engine;
    String host;
    Integer port;
    String dbname;
    String dbInstanceIdentifier;

    public static Settings fromJson (String jsonData) {
        Gson gson = new Gson();
        return gson.fromJson(jsonData, Settings.class);
    }
}

JSONObject:

 class Settings {
    String username;
    String password;
    String engine;
    String host;
    Integer port;
    String dbname;
    String dbInstanceIdentifier;

    public static Settings fromJson (String jsonData) {
        JSONObject json = new JSONObject(jsonData);
        Settings newSettings = new Settings();
        newSettings.username = json.getString("username");
        newSettings.password = json.getString("password");
        newSettings.engine = json.getString("engine");
        newSettings.host = json.getString("host");
        newSettings.port = json.getInt("port");
        newSettings.dbname = json.getString("dbname");
        newSettings.dbInstanceIdentifier = json.getString("dbInstanceIdentifier");
        return newSettings;
    }
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Johannes H.
  • 5,875
  • 1
  • 20
  • 40