I'd like to get the requestedInstanceCount
from instanceGroupName
= slave
. How can this be achieved with Jackson?
Below is the job-flow.json
:
{
"generalId": "ABC"
"instanceCount": 4,
"instanceGroups": [
{
"instanceGroupId": "CDE",
"instanceGroupName": "master",
"requestedInstanceCount": 1
},
{
"instanceGroupId": "FGH",
"instanceGroupName": "slave",
"requestedInstanceCount": 8
}
]
}
So far this is what I have:
val jobFlowJson: String = new String(Files.readAllBytes(Paths.get("/mnt/var/lib/info/job-flow.json")))
val jsonNode = mapper.readValue(jobFlowJson, classOf[JsonNode])
val instanceCount = jsonNode.get("requestedInstanceCount").asInt
But there are 2 values and the order between master & slave can change at any time. Thanks in advance!
CodePudding user response:
You have to go through the JSON tree step by step:
- get the
instanceGroups
as an array - iterate over the array to find the item you want
- extract the value
requestedInstanceCount
Something like this (pseudo Scala code):
jsonNode.get("instance groups")
.asArray
.collect {
case item if item.get("instanceGroupName").asString == "..." =>
item.get("requestedInstanceCount")
}
Or define some case class representing the structure and parson your JSON into the case class. It will be way easier to manipulate if you have no specific reason to not do this.