1

I am facing a problem converting json object to POJO class.

I have a public class called Service and it has an inner class User. I want to use the inner class as a container/object to hold the variables for all my outer class methods. I am trying to do the below, but I am getting compilation errors. Please show how I can do this and please correct the mistake I am doing in my code below.

From eclipse debug window, i see the below json being obtained in node variable node : {"firstName":"ndndbs","lastName":"dnjdnjs"}

Trial 1:

public class Service {
                             // Method
public boolean createUserAccount(JsonNode node) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
         User user=null;
        try {
            Service service=new Service();
            user = mapper.readValue(node, User.class);    
        } catch (Exception e) {throw new Exception("failed to bind json", e);}

     System.out.println("Use this anywhere in method"+userNode.firstName); 
    }

}
                               // Inner class
public class User {
        public String firstName;
        public String lastName;
    }
        }

OUTPUT:
NULL POINTER EXCEPTION AND user=null even after execution of mapper.readValue() statement
pret
  • 273
  • 3
  • 6
  • 18

1 Answers1

0

From the statement

user = mapper.readValue(node, User.class);  

Not sure about cause for NullPointerException (a full stacktrace might help ). It appears ObjectMapper is trying to create instance of inner class via Reflection. But creating instance of inner and nested classes is not straight forward See Is it possible to create an instance of nested class using Java Reflection? .

in your case

Service.User.class.class.getConstructors()[0].newInstance(serviceInstance);

instead of

User.class.newInstance() 

which would have been a case with Usual/Outer classes. I am not sure if ObjectMapper is equipped to instantiate class this way.

I suggest moving the User to a top level public class in its own source User.java unless you have a specific design restriction which I am curious to know.

Community
  • 1
  • 1
Prashant Bhate
  • 10,907
  • 7
  • 47
  • 82