0

I have a Java bean defined as follows:

public class Person {

    private String name;
    private String surname;

    public Person(String name, String surname) {
        this.name = name;
        this.surname = surname;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return this.surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }
}

I've written this simple REST method and if I pass via POST:

{ "name": "John", "surname": "Doe"}

it works.

import com.google.gson.Gson;

@Path("/person")
public class PersonRestService {
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response getMsg(String inputJsonObj) {

        Persona p = new Gson().fromJson(inputJsonObj, Person.class);

        System.out.println("Name: " + p.getName());
        System.out.println("Surname: " + p.getSurname());

        return Response.status(200).build();
    }
}

But why have I to accept a String as an input field of the method?

I've tried to accept a Person object in the getMsg method and still passing a JSONObject like this:

{ "name": "John", "surname": "Doe"}

but I got an HTTP Status 415 – Unsupported Media Type.

What is the easiest way to receive a Person object directly in the method without parsing it with Gson once inside the method?

Thanks in advance :)

Roberto Milani
  • 760
  • 4
  • 20
  • 40

1 Answers1

1

but I got an HTTP Status 415 – Unsupported Media Type.

You need a JSON Provider. Also make sure your POJO has a default constructor.

If you're using Maven, you can just add the following dependency

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>${jersey2.version}</version>
</dependency>

If you're manually adding jars, check out this post.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Thanks a lot, it works! The JSON Provider was missing :) Why don't use jersey-media-json-jackson which is Jersey JSON Jackson (2.x)? – Roberto Milani Jul 11 '17 at 15:04
  • 1
    Sorry, you _should_ use that one (I fixed it). I just grabbed the first one from the link. I Forgot they have a dependency for Jackson 1. – Paul Samsotha Jul 11 '17 at 15:06