Skip to content
Advertisement

Trying to search through JSON in Java

I am using the Marvel API to try and get the names of heroes based on what the user has typed inside of the search box. The search functionality works I am pretty sure as it will search through a regular array however I am trying to make it search through a JSONArray. Below is what I have so far.

JavaScript

This is the part I am pretty sure is the problem because I do not think it is going to the part of the JSON which has the name inside of it. There is an example JSON below where the results are when the user searches the word “captain”

JavaScript

I need to know why it won’t only add the name part of the JSON to the JSONArray. All that happens currently is that when the user searches something nothing appears when trying it this way. Any help is appreciated.

Advertisement

Answer

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:

String name_i = results.getJSONObject(i).getString("name")

Hope this helps.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement