0

I'm making a Java application for school in which I want to fetch data from an API in JSON format. More precisely, I fetch a list of objects. Each object contains data about one thing, let's say movie data.

The returned data looks like this: {"page":1,"total_results":102,"total_pages":6,"results":[{"vote_count":13240,"id":597,"video":false,"vote_average":7.8,"title":"Titanic"}]}.

Now, for each row of movies in "results", I want to show the name in a JTable. Right now the code looks like:

String text = searchField.getText();
String url = "https://api.themoviedb.org/3/search/movie?api_key=SECRET&query=" + URLEncoder.encode(text, "UTF-8");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

int responseCode = con.getResponseCode();

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

String inputLine;
StringBuffer buffer = new StringBuffer();
while((inputLine = in.readLine()) != null)
{
     buffer.append(inputLine);
}
in.close();


DefaultTableModel table = new DefaultTableModel();
table.addColumn("Title");
jTable.setModel(table);

Now I'm a bit stuck. Where do I go from here?

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Frederik
  • 637
  • 2
  • 8
  • 21
  • 1
    Maybe a custom `TableModel`, like [this](https://stackoverflow.com/a/9134371/230513) or [this](https://stackoverflow.com/a/25418826/230513). – trashgod Feb 20 '19 at 10:41

1 Answers1

1

Best way would be follow the MVC design pattern and create a class in order to represent these JSON lines into Objects. Then use an already existing library to parse the values into the object. Most common (i think) library for this job out there, is GSON.

After that, instead of some JSON lines, you will have Objects with properties. Let's see an example:

Assume you get JSON lines (of Persons) like this:

{"name":John, "age":34}

Now instead of messing with this kind of Strings, you create a class Person:

public class Person {
    private String name;
    private int age;

    public Person() {
        // JSON parsers need a declared default (no argument) constructor
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Then with a simple:

Gson gson = new GsonBuilder().create();
Person p = gson.fromJson(myJsonString, Person.class);

You have a person with the values of this JSON string.

Finally: You read this question and all of your problems are solved. Clean and soft.

George Z.
  • 6,643
  • 4
  • 27
  • 47