1

I am tasked with creating a simple web api using JAVA EE and I cant use other external frameworks such as Spring Boot.

I got the get requests to work that was simple, however when I try to return a JSON to the api all I see is {} in postman or browser even though I created a user.

here is my current code

package ab.service;

import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

@Path("/MyRestService")
@ApplicationPath("resources")
public class RestService extends Application {
    // http://localhosts:8080/BankTaskV1/ressources/MyRestService/sayHello
    @GET
    @Path("/sayHello")
    public String getHelloMsg() {
        return "Hello World";
    }

    @GET
    @Path("/echo")
    public Response getEchoMsg(@QueryParam("message") String msg) {
        return Response.ok("you message was:  " + msg).build();
    }

    @GET
    @Path("/User")

    public Response getUser() {
//      Gson gson = new Gson();
        User user = new User(1, "Ahmad");
        return Response.status(Response.Status.OK).entity(user).type(MediaType.APPLICATION_JSON).build();
//      return gson.toJson(user);
    }

    @POST
    @Path("/CreateUser")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public void createUser(UserRequest requestBody) {
        System.out.println("create ran");
        System.out.println(requestBody.UserName);

    }

}

as you can see in the User endpoint I used GSON to convert user object to a json string and that worked, however I read online that it should work without it if I did it by returning an entity, something called POJO?

but that just gives me an empty {}

furthermore in the endpoint CreateUser I set it to consume json and gave it a request body with class that i defined. but when I try to print the username it gives me null, andd the create ran system output shows that the function ran.

here is my User class

package ab.service;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class User {
    private int id;
    private String name;

    public User() {
    }

    public User(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    String getName() {
        return name;
    }

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

    int getId() {
        return id;
    }

    void setId(int id) {
        this.id = id;
    }
}

and my userrequest class

package ab.service;

import javax.xml.bind.annotation.XmlRootElement;

import jakarta.xml.bind.annotation.XmlElement;

@XmlRootElement
public class UserRequest {

    @XmlElement
    String UserName;
    @XmlElement
    int Id;
}
MrAbdul
  • 76
  • 3
  • 11

0 Answers0