3

Helo Everyone. I am new to jersey and Jackson and finding it really difficult to deserialize a JSOn response from my REST service on client side. I am pretty sure that I am still not grasping the Object mapper and JSON provider APIs that well. Any help or guidance is appreciated in advance. Here is my source code.

Source Code

POJO Class

    @XmlRootElement(name = "user")
    public class User  implements Serializable{

        private String firstName;
        private String lastName;
        private String email;
        private String userID;

        public User() {

        }



        public User(String firstName, String lastName, String email, String userID) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.email = email;
            this.userID = userID;
        }



        public String getFirstName() {
            return firstName;
        }
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
        public String getLastName() {
            return lastName;
        }
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public String getUserID() {
            return userID;
        }
        public void setUserID(String userID) {
            this.userID = userID;
        }



    }

Client Code

package com.example.service.client;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.jackson.JacksonFeature;

import com.example.service.bean.User;
import com.example.service.client.mapper.MyMessageBodyReader;
import com.example.service.client.mapper.MyObjectMapperProvider;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;


public class GetJSONResponse {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JacksonJaxbJsonProvider provider1 = new JacksonJaxbJsonProvider();
        Client c = ClientBuilder.newClient()register(provider1);//.register(mapper); 
        WebTarget target = c.target("http://localhost:8080/RestfulWebserviceExample").path("/jaxrs/user/Nishit");

        Response resp = target.request(MediaType.APPLICATION_JSON).get();
        System.out.println(resp.getStatus());
        String user1  = resp.readEntity(String.class);
        System.out.println(user1);

        User user  = target.request(MediaType.APPLICATION_JSON).get(User.class);
        System.out.println("User : " + user.getUserID());           

    }

}

` The first 2 sysout generates an output as

200

{"user":{"firstName":"Nishit","lastName":"Ladha","email":"ladha@us.ibm.com","userID":"nishiz"}}

But when i tries to directly get the User object from response, I get an error as

Exception in thread "main" javax.ws.rs.client.ResponseProcessingException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "user" (class com.example.service.bean.User), not marked as ignorable (4 known properties: "lastName", "firstName", "email", "userID"])
 at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@10163d6; line: 1, column: 10] (through reference chain: com.example.service.bean.User["user"])
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:806)
    at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:700)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:696)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:316)
    at com.example.service.client.GetJSONResponse.main(GetJSONResponse.java:40)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "user" (class com.example.service.bean.User), not marked as ignorable (4 known properties: "lastName", "firstName", "email", "userID"])

It will be really kind if anyone of you can guide me how to resolve this.

I am not using Maven as I first wanted to try without Maven

I am not sure why my rest service is wrapping the response. Here is the code :

Service Method

@GET
@Path("/{username}")    
@Produces(MediaType.APPLICATION_JSON)
public User helloWorld(@PathParam("username") String name){
    User user = new User();
    user.setFirstName("Nishit");
    user.setLastName("Ladha");
    user.setUserID("nishiz");
    user.setEmail("ladha@us.ibm.com");      
    return user;
}

Web.xml##

<servlet>
<description>JAX-RS Tools Generated - Do not modify</description>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
    <param-name>jersey.config.server.provider.packages</param-name>
    <param-value>
        com.example.service,
        com.fasterxml.jackson.jaxrs.json
    </param-value>
</init-param>
<init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>

Puce
  • 37,247
  • 13
  • 80
  • 152
nishiz
  • 55
  • 8

1 Answers1

-1

Man, look, you are trying to bind unexistent field User. If you want to properly parse this json

{"user":{"firstName":"Nishit","lastName":"Ladha","email":"ladha@us.ibm.com","userID":"nishiz"}}

You need to have similar to this class

public class UserWrapper implements Serializable{

    private User user;
    // Constructors
    // Getters, and setters
    // HashCode and equals
}

Then this client code will work:

public class GetJSONResponse {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JacksonJaxbJsonProvider provider1 = new JacksonJaxbJsonProvider();
        Client c = ClientBuilder.newClient()register(provider1);//.register(mapper); 
        WebTarget target = c.target("http://localhost:8080/RestfulWebserviceExample").path("/jaxrs/user/Nishit");

        Response resp = target.request(MediaType.APPLICATION_JSON).get();
        System.out.println(resp.getStatus());
        String user1  = resp.readEntity(String.class);
        System.out.println(user1);

        UserWrapper userWrapper  = target.request(MediaType.APPLICATION_JSON).get(UserWrapper.class);          

    }

}

If you have any questions - just ask.Hope your code will work.

Ivan Ursul
  • 3,251
  • 3
  • 18
  • 30