1

I want to find whether a key-value pair exists in a JSON given a key. This key-value pair may not be under root. It's possible embedded deeply in the document. For example:

{"Persons":[
  {"Person":
    {"name":"john"}
  }]
}

and I want to have something like JsonDoc.has("name"), and return true. I search online and find this thread: Java: Json has key/field

Two answers (minimal-json and org.json) both has some functioned called has() or get(), but I looked into their source code, they are both trying to find the key-value under root. So they don't meet my needs.

I can think of traversing the whole json and try to find the key-value, but it seems not efficient.

3
  • 4
    How do you expect to search the whole tree without searching the whole tree (traversing it)? Commented Jul 9, 2015 at 22:16
  • So... I'm looking for a good algorithm, or a library that has already implement some algorithm for me. Hopefully later one... Commented Jul 9, 2015 at 22:28
  • Use Gson Commented Jul 9, 2015 at 22:30

1 Answer 1

1

If you use Jackson, you can call findParent on a JsonNode which will look for a field within the node or its descendant.

http://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/JsonNode.html#findParent(java.lang.String)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.