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;
}
}