2

I am feeling kind of lost since I already struggled with some dependencies in my pom.xml, but what I am trying to do is to extract a single property from a JSON in my Spring Boot Application.

I have a FilmServiceClient, declared as FeignClient which fetches some data from IMDb, which looks as following:

{
    "Title": "Kingsman: The Secret Service",
    "Year": "2014",
    "Rated": "R",
     [...]
    "Metascore": "60",
    "imdbRating": "7.7",
    "imdbVotes": "597,264",
     [...]
}

In my FilmService, I would like to implement a getRating method which extracts the imdbRating from the JSON as double attribute, which I eventually want to add to the Film entity in my DB.

I am grateful for every advise as well as the necessary dependencies and imports, thank you in advance!

Nicolorino
  • 41
  • 1
  • 5
  • 1
    It sounds like you want to familiarize yourself with Jackson. It's easy/painless: honest. https://www.tutorialspoint.com/jackson/, https://www.baeldung.com/jackson, https://www.baeldung.com/jackson-object-mapper-tutorial – paulsm4 May 10 '21 at 18:00

3 Answers3

2

Thanks to paulsm4, I studied the information from baeldung.com/jackson and could extract the necessary data perfectly :)

If interested, this is how my code looks like now:

    protected String getRating(String title) throws Exception{
        String rating;
        String film = fsc.getFilmInfo(title);
        try{
            ObjectMapper mapper = new ObjectMapper();
            JsonNode tree = mapper.readTree(film);
            JsonNode node = tree.get("imdbRating");
            rating = node.textValue();
        }
        catch(Exception e){
            rating = "0.0";
        }
        return rating;
    }

As result, it returns "7.7" as String as stated in the JSON above.

Thanks and have a good night!

Nicolorino
  • 41
  • 1
  • 5
0

You can convert json string to object as below. Then you can access properties of film object.

Here Film is POJO with same properties defined in json string

import com.fasterxml.jackson.databind.ObjectMapper;
Film film = new ObjectMapper().readValue(jsonString, Film.class);

Film POJO

public class Film {

    private String title;
    private double imdbRating;
    [...]
    // getters and setters


    }

sanjeevRm
  • 1,541
  • 2
  • 13
  • 24
0

You can do:

ObjectMapper objectMapper = new ObjectMapper();
    
double imdbRating = objectMapper.readTree(json).findValue("imdbRating").asDouble();
System.out.println(imdbRating);

Output:

7.7

If you don't seem to have ObjectMapper, you can add the dependency in pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.1</version>
</dependency>
Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12