It should look like this:

boolean found = false;
for (int i = 0; i < jsonArray.length(); i++)
    if (jsonArray.getString(i).equals(myElementToSearch))
        found = true;

I assume that jsonArray has type http://www.json.org/javadoc/org/json/JSONArray.html.

Answer from kraskevich on Stack Overflow
🌐
Tabnine
tabnine.com › home page › code › java › org.json.jsonarray
org.json.JSONArray.get java code examples | Tabnine
Get the JSONArray associated with an index. ... This class generates cryptographically secure pseudo-random numbers. It is best to invoke SecureRand ... This class contains various methods for manipulating arrays (such as sorting and searching). This cl ... A parser that parses a text string of primitive types and strings with the help of regular expressio ... A plug-in replacement for JDK1.5 java.util.concurrent.ConcurrentHashMap.
🌐
Stack Overflow
stackoverflow.com › questions › 61000522 › find-jsonobject-in-jsonarray-javax-json-jsonarray-by-key-or-value-using-java-8
Find JsonObject in JsonArray (javax.json.JsonArray) By Key or Value Using Java 8 Lambas - Stack Overflow
Since JsonArray is a List<JsonValue>, you can call stream() on it. To locate something, you'd use filter(...) and findFirst(). Those are all fairly simple, and there are many examples of their use on the web, so what have you tried, and how ...
🌐
Stack Overflow
stackoverflow.com › questions › 62364306 › trying-to-search-through-json-in-java
arrays - Trying to search through JSON in Java - Stack Overflow
All that happens currently is that when the user searches something nothing appears when trying it this way. Any help is appreciated. ... If I'm understanding this correctly, the name field is a string, which is an element of the results array, which is itself a child of the data JSON object. To access the results array, try: JSONArray results = jsonObject.getJSONObject("data").getJSONArray("results") You can then access the individual result name at index i like this:
Find elsewhere
🌐
JAXB
javaee.github.io › javaee-spec › javadocs › javax › json › JsonArray.html
JsonArray (Java(TM) EE 8 Specification APIs)
This is a convenience method for (JsonArray)get(index). ... Returns the number value at the specified position in this array.
🌐
Stack Overflow
stackoverflow.com › questions › 68116547 › search-for-a-specific-value-in-json-array
java - Search for a specific value in JSON array - Stack Overflow
One simple way would be to convert the string to a JSON Array and then use it in anyway you like: import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class Test { public static void main(String[] args) throws JSONException { String oktas = "{{\"accountNumber\" : \"13176704\", \"paperless\" : \"true\", \"emailable\" : \"true\"},{\"accountNumber\" : \"13176704\", \"paperless\" : \"true\", \"emailable\" : \"true\"}}"; JSONArray jsonArr = new JSONArray(oktas); for (int i = 0; i < jsonArr
🌐
Baeldung
baeldung.com › home › json › get a value by key in a jsonarray
Get a Value by Key in a JSONArray | Baeldung
January 8, 2024 - Learn how to parse a JSONArray to get all the mapped values for a given key.
🌐
TutorialsPoint
tutorialspoint.com › how-to-search-a-value-inside-a-json-file-using-jackson-in-java
How to search a value inside a JSON file using Jackson in Java?
The com.fasterxml.jackson.databind.node.ObjectNode class can be used to map the JSON object structure in Json content. We can search for a particular value inside the JSON file using the get() method of ObjectNode class, this method used for accessing the value of a specified field of an object node
Top answer
1 of 4
19

You can also use the JsonPath project provided by REST Assured. This JsonPath project uses Groovy GPath expressions. In Maven you can depend on it like this:

<dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

Examples:

To get a list of all book categories:

List<String> categories = JsonPath.from(json).get("store.book.category");

Get the first book category:

String category = JsonPath.from(json).get("store.book[0].category");

Get the last book category:

String category = JsonPath.from(json).get("store.book[-1].category");

Get all books with price between 5 and 15:

List<Map> books = JsonPath.from(json).get("store.book.findAll { book -> book.price >= 5 && book.price <= 15 }");

GPath is very powerful and you can make use of higher order functions and all Groovy data structures in your path expressions.

2 of 4
1

Firstly, add json-path dependency in pom

<dependency>
     <groupId>com.jayway.jsonpath</groupId>
     <artifactId>json-path</artifactId>
     <version>2.2.0</version>
</dependency>

Create a utility in Base Class that can be reused :

 public static String getValueFromJsonPath(String apiResponse, String jsonPath) {
        return JsonPath.read(apiResponse, jsonPath);
    }

One example of using this method :

getValueFromJsonPath(apiResponse, "$.store.book[0].category");

NOTE : Create overloaded method with different return types depending upon the expected result (like List for fetching a list from json)

Top answer
1 of 1
5

This could work: $[?(@[2] == 'Some name 2')][1]

Background:

If you try the "original" JSONPath implementation written by Stefan Goessner, the following expression returns the expected array:

$..[?(@[2] == 'Some name 2')] (a descendant where value at index 2 is 'Some name 2')

===> ["Some parent 2"]

It is interesting... try these expressions with jayway, Goessners-JSON-lib or jsonquerytool :

"$..*" //list of all descendants (both child-arrays + elements in arrays)
"$.*" //list of all direct children (both child arrays)
"$" //actual element (the array itself)

Stefan Goessner's JavaScript library returns the same as the "jayway" implementation. But "jsonquerytool" gives false for $ - which is definitively wrong. $ is "the root object/element".

And for $..* this is the same result with all three implementations:

[
    [
        "Some short name",
        "Some parent",
        "Some name"
    ],
    [
        "Some short name 2",
        "Some parent 2",
        "Some name 2"
    ],
    "Some short name",
    "Some parent",
    "Some name",
    "Some short name 2",
    "Some parent 2",
    "Some name 2"
]

So $..[?(@[2] == 'Some name 2')] should match the array at index '1'... in my opinion, jayway is doing it wrong.

With JSONPath square brackets operate on the object or array addressed by the previous path fragment. (see http://goessner.net/articles/JsonPath/)

Goessner is the inventor of JSONPath - so his implementation is doing it the right way!!! summary: jsonquerytool's and jayway's implementations are wrong.

Surprisingly this query is working as expected in all implementations (although $ is false in jsonquerytool)

$[?(@[2] == 'Some name 2')][1]

also this version works:

$.[?(@[2] == 'Some name 2')][1]
🌐
Baeldung
baeldung.com › home › json › how to check if a value exists in a json array for a particular key
How to Check if a Value Exists in a JSON Array for a Particular Key | Baeldung
January 8, 2024 - In this article, we saw that we can use both Jackson and Gson to check if a value exists for a selected property in a JSON array. Both implementations were similar. They ultimately implemented the plan of parsing the JSON, converting it to a Stream, and then finally using the Stream utilities to check for a match.
🌐
Stack Overflow
stackoverflow.com › questions › 8242939 › how-to-search-a-jsonarray-inside-the-jsonobject-in-java
json - how to search a JSONArray inside the JSONObject in JAVA - Stack Overflow
It's not a database, it's a flat file that is being passed in, you have to search it one record at a time. ... That filter goes through each record. If you're trying to save time it's the same thing. You have to reduce it before you load the json.