Reputation: 121
I want to read a JSON file received.
That's the form of the JSON file:
{
"name": "list_name"
"items": [
{
"id": 4
},
{
"id": 3
},
{
"id": 2
},
]
}
I want to parse that JSON that represents a movie list, and the id's of the movies. I want to extract the ids and the name.
@PUT
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
public Response deleteMoviesFromList2(@Context HttpServletRequest req) Long movieListId) {
Long userId = getLoggedUser(req);
getLoggedUser(req);
final String json = "some JSON string";
final ObjectMapper mapper = new ObjectMapper();
return buildResponse(listMovieService.remove(¿?));
}
I want to extract the ids but I have no clue how to do it.
Upvotes: 3
Views: 15899
Reputation: 45309
If you have a movie class defined, such as:
class Movie {
String id;
//getters
//setters
}
and a Movie list class:
class MovieList {
String name;
List<Movie> items;
//getters
//setters
}
Then you can use an object mapper with an inputStream:
try(InputStream fileStream = new FileInputStream("movielist.json")) {
MovieList list = mapper.readValue(fileStream, MovieList.class);
}
ObjectMapper
's readValue has an overloaded version that takes an input stream, and that's the one used above.
Upvotes: 1
Reputation: 1951
You can convert json string using ObjectMapper class like this.
ObjectMapper objectMapper = new ObjectMapper();
String carJson =
"{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
try {
Car car = objectMapper.readValue(carJson, Car.class);
System.out.println("car brand = " + car.getBrand());
System.out.println("car doors = " + car.getDoors());
} catch (IOException e) {
e.printStackTrace();
}
Here you can replace Car class with your custom Movie class and you are done.
Upvotes: 1