Reputation: 51
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!
Upvotes: 3
Views: 5667
Reputation: 2776
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>
Upvotes: 0
Reputation: 51
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!
Upvotes: 2
Reputation: 1606
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
}
Upvotes: 0