Skip to content
Advertisement

Parsing multiple JSON objects that exist in one line in Java

I’m currently using the OMDB API, which can either return get-queries as JSON objects or XML. Working with JSON is something I’d like to learn, and it generally seems like best solution for what I’m trying to do. The implementation I’m hoping for, is to allow the user to search for a movie, and select the correct one from a list. I’m currently using the google.gson library.

The problem I’ve run in to, is that the searching for movies by a title with OMDB, this example being “batman”, returns the following String:

JavaScript

Thus far, I’ve managed to remove the {"Search":[ and ],"totalResults":"490","Response":"True"} part using sendGetRequest(requestURL).substring(11, sendGetRequest(requestURL).length()-41);, yet I still can’t seem to parse the String as JSON. I’ve tried using String.split and Matcher/Pattern with various regexes, to separate the the JsonObjects. I’ve also tried a JSONArray, but to no avail.

I’m new to working with JSON, so it’s not unlikely I’m missing something obvious or have completely misunderstood JSON in general.

Advertisement

Answer

First define a new custom class for your need:

JavaScript

Then simply you can parse your JSON, this is main method:

JavaScript

P.S: Keep in your mind that you must not remove brackets [] from your JSON as you said in your question.

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