I have this java code that retrieves the values from a secret
public class fetchSecrets {
public static void main(String[] args) {
String secretId = "test";
SecretsManagerClient secretsClient = SecretsManagerClient.builder()
.region(Region.EU_WEST_1)
.build();
fetchPassword(secretsClient, secretId);
secretsClient.close();
}
public static void fetchPassword(SecretsManagerClient secretsClient,String secretId){
try {
GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
.secretId(secretId)
.build();
GetSecretValueResponse valueResponse = secretsClient.getSecretValue(valueRequest);
String secret = valueResponse.secretString();
System.out.println(secret);
} catch (SecretsManagerException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
}
when i run this, i get:
{"username":"test","password":"password123456"}
How do i output only the value of the password or the username keys?
so expected output is e.g. password123456
CodePudding user response:
I suggest doing the following: first, create a class called User like this:
public class User{
private String username;
private String password;
//setter
void setUsername(String username){
this.username = username;
}
void setPassword(String password){
this.password = password;
}
//getter
String getUsername(){
return this.username;
}
String getPassword(){
return this.password;
}
}
then you can retrieve the password like this:
User user = gson.fromJson(secret , User.class);
System.out.println(user.getPassword());
CodePudding user response:
Turns out I had to create a json object and pass in the string to extract its value:
try {
GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
.secretId(secretId)
.build();
GetSecretValueResponse valueResponse = secretsClient.getSecretValue(valueRequest);
String secret = valueResponse.secretString();
//defining a JSON string
Object obj=JSONValue.parse(secret);
//creating an object of JSONObject class and casting the object into JSONObject type
JSONObject jsonObject = (JSONObject) obj;
//getting values form the JSONObject and casting that values into corresponding types
String username = (String) jsonObject.get("username");
//printing the values
System.out.println(username);
} catch (SecretsManagerException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Output : password123456