Reeves62
Reeves62

Reputation: 149

Reading a JSON Object from a POST request in java

I have a post request that looks to insert a Film into my database.

Currently the request works (when testing with postman) when I enter each section of information needed to create a new film object in the query Params...

title:TEST
year:2021
director:TEST
stars:TEST
review:TEST

my Post method

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    FilmDAO dao = new FilmDAO();        
    PrintWriter pw = response.getWriter();
    
    String title = request.getParameter("title");
    int year = Integer.valueOf(request.getParameter("year"));
    String director = request.getParameter("director");
    String stars = request.getParameter("stars");
    String review = request.getParameter("review");
    
    Film f = new Film(title, year, director, stars, review);
    
    dao.insertFilm(f);
}

I need my post method to also work if the film is passed in as a JSON or XML object but I'm not sure how to do this.

I have tried

 StringBuilder sb = new StringBuilder();
    BufferedReader reader = request.getReader();
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } finally {
        reader.close();
    }
    System.out.println(sb.toString());

which gets the json object and displays this: [{"title":"TEST","year":2021,"director":"TEST","stars":"tests","review":"test"}]

but I'm not sure how to use that string to then call my insert method

Upvotes: 0

Views: 735

Answers (1)

oktaykcr
oktaykcr

Reputation: 376

You can solve your problem with Spring Boot Framework easily.

In Spring Boot, you just add "consumes" and "produces" keys into annotation.

@PostMapping(
        consumes = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }, 
        produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }
)
public MyResponse doPost(@RequestBody Film film) 
{
  MyResponse response = new MyResponse();
  response.setData(film);
  return response;
}

For your solution, you need to following dependencies (Maven package manager) for converting xml or json string to Film object. Then you can use Film object to save in the database.

For Json:

<dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.12.1</version>
</dependency>

For XML:

<dependency>
     <groupId>com.fasterxml.jackson.dataformat</groupId>
     <artifactId>jackson-dataformat-xml</artifactId>
     <version>2.11.1</version>
</dependency>

Code Example:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.util.List;

public class RestAssuredDemo {

    public static void main(String[] args) {
        String filmJson = """
                  {
                    "title": "TEST",
                    "year": 2021,
                    "director": "TEST",
                    "stars": "tests",
                    "review": "test"
                  }
                
                """;

        String filmXml = """
                  <film>
                    <title>TEST</title>
                    <year>2021</year>
                    <director>TEST</director>
                    <stars>tests</stars>
                    <review>test</review>
                  </film>
                """;

        XmlMapper xmlMapper = new XmlMapper();
        Film xmlFilm = null;
        try {
            xmlFilm = xmlMapper.readValue(filmXml, Film.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        ObjectMapper om = new ObjectMapper();
        Film film = null;
        try {
            film = om.readValue(filmJson, new TypeReference<>() {});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public static class Film{
        public String title;
        public int year;
        public String director;
        public String stars;
        public String review;
    }

Upvotes: 2

Related Questions