Read a JSON file using JACKSON

14,246

Solution 1

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.

Solution 2

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.

Share:
14,246
Arnau Van Boschken ArnauB
Author by

Arnau Van Boschken ArnauB

Updated on June 18, 2022

Comments

  • Arnau Van Boschken ArnauB
    Arnau Van Boschken ArnauB almost 2 years

    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.

    • niceman
      niceman almost 6 years
    • niceman
      niceman almost 6 years
      if I recall you only need to add jackson jars to the classpath and jersey will use them to convert any json to any class you want and vice versa
    • niceman
      niceman almost 6 years
      ofcourse your class needs to be a (pseudo) JavaBean
  • Arnau Van Boschken ArnauB
    Arnau Van Boschken ArnauB almost 6 years
    But I don't have the carJson var. I received a JSON from a PUT call.
  • DeepInJava
    DeepInJava almost 6 years
    You can take your json string in some string variable and then convert to equivalent object using Object mapper.