I am using JsonPath to retrieve a value from a JSON file. The JSON file looks something like this:
[
{
"username": "John",
"password": {
"passwordValue": "passwordjohn",
"secret_key": "123"
}
},
{
"username": "Nick",
"password": {
"passwordValue": "XXX",
"secret_key": "ZZZ",
"other_key": "YYY"
}
}
]
The JsonPath I am using is to retrieve the password
from a particular user. Example:
fun getPassword() {
val passwords: JSONArray = read(jsonFile, "\$.[?(@.name==\"John\")].password")
}
However, I found two obstacles. Firstly, I get back a net.minidev.json.JSONArray
always, and the same path with appended [0]
doesn't work.
Therefore, I try to get the only element from the JSONArray
I get back, like this: credentials[0]
. Unfortunately, this removes the double quotes in the field names, resulting in something like this:
{passwordValue: passwordjohn, secret_key: 123}
Which is impossible to work with.
I am looking for a way to get this back:
{"passwordValue": "passwordjohn", "secret_key": "123"}
What I ended up doing was to remove the [
and ]
symbols from the beginning of the JSONArray
after converting it to a String
:
private fun JSONArray.toCredentialString(): String {
val credentialString = this.toString()
return credentialString.substring(1, credentialString.length - 1)
}
Any better solution is welcome.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.