Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a JSON file using JACKSON

Tags:

java

json

parsing

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.

like image 991
Arnau Van Boschken ArnauB Avatar asked Jan 24 '26 12:01

Arnau Van Boschken ArnauB


1 Answers

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.

like image 145
DeepInJava Avatar answered Jan 27 '26 01:01

DeepInJava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!