当前位置: 动力学知识库 > 问答 > 编程问答 >

Find JSON sibling with no parent using JsonNode in java

问题描述:

I have a JSON object as follows:

[

{

"name":"thisIsAName",

"id":1

},

{

"name":"anotherName",

"id":2

},

{

"name":"anotherName2",

"id":3

}

]

and am trying to locate the id based on the name. How do you navigate to the sibling when there is no parent? I'm getting the JSON from a Jersey Client response:

Response responseObject = client.getAllObjects();

JsonNode responseAsNode = responseObject.readEntity(JsonNode.class);

If I search by name: responseAsNode.findValue("name");, then it correctly gives me a List<JsonNode> that contains every name element, so I can search that for the one that matches my expected, but it only returns a list of JsonNodes of "name":"value",.

for (JsonNode node : responseAsNode.findValues("name")){

if (node.textValue().equals("ftp-" + DEFAULT_ENV.toLowerCase())) {

//Now, find my id and do something with it.

break;

}

}

If I call node.getParent(), I get an exception as there is no parent. Other than asking the developers to add "list": to the front of the Json, what should I try?

网友答案:

Navigate the JSON tree, and try to match each element.

String toFind = "anotherName";

Iterator<JsonNode> iter = responseAsNode.elements();

while (iter.hasNext())
{
    JsonNode node = iter.next();

    JsonNode name = node.get("name");

    if (toFind.equals(name.asText()))
    {
        System.out.println(node.get("id").asLong());
    }

}

This will print 2.

分享给朋友:
您可能感兴趣的文章:
随机阅读: