1

I have a method in a Spring MVC controller as follows:

// Gets a Person via REST.

@RequestMapping(value="/person/{personId}", method=RequestMethod.GET)
public ModelAndView getPerson(@PathVariable("personId") String personId) {

    logger.info(RestController.class.getName() + ".getPerson() method called."); 

    Person person = personService.get(Integer.parseInt(personId));
    return new ModelAndView(view,"person", person);        
} 

The method is working correctly but in the code to process the JSON on the client, I get the following exception:

Unrecognized field "person" (class libraryApp.model.Person), not marked as ignorable (6 known properties: , "personId", "address", "telephone", "books", "name", "email"])

The code is below:

// Set request.
        String url = ("http://localhost:8080/Library/rest/person/1");      
        HttpGetRequest httpGetRequest = new HttpGetRequest(url, "GET", ""); 

        // Make request.
        httpGetRequest.get();

// Get response.        
        if (httpGetRequest.getResponseCode() != 200) {                  
            throw new RuntimeException("Get request failed: HTTP error code: " + httpGetRequest.getResponseCode());
        } 
        else {                                      

            // Receive JSON from server and convert to Person.
            ObjectMapper mapper = new ObjectMapper(); 
            Person person = mapper.readValue(httpGetRequest.getResponse(), Person.class);
            System.out.println("Person:");
            System.out.println(person.toString());
            if (! (person.getBooks().isEmpty())) {
                System.out.println("Books:");
                for (Book book : person.getBooks()) {
                    System.out.println(book.toString());
                }
            }
        }

Person is a simple POJO as follows:

public class Person implements Serializable {

// Attributes.        
private Integer personId;        
private String name;  
private String address;   
private String telephone;       
private String email;        
private List<Book> books;

I am using ModelAndView constructor, ModelAndView(String viewName, String modelName, Object modelObject). So according to the JavaDoc I have to specify a modelName but how can I deal with this on the client?

Now I am getting no response on the client from the following if I use a class called Messages in the following code:

ObjectMapper mapper = new ObjectMapper(); 
            Object obj =  mapper.readValue(httpGetRequest.getResponse(), Object.class);
            if (obj instanceof Messages) {
              Messages m = (Messages) obj;
              for (String s : m.getMessages())
                  System.out.println("Here " + s);


            }

Messages is a utility class:

public class Messages {

private List<String> messages;

public Messages() { 
    messages = new ArrayList<String>();
}

With the controller method now:

@RequestMapping(value="/person/{personId}", method=RequestMethod.GET)

@ResponseBody public String getPerson(@PathVariable("personId") String personId) {

logger.info(RestController.class.getName() + ".getPerson() method called."); 

Person person = personService.get(Integer.parseInt(personId));

ObjectMapper mapper = new ObjectMapper();
try {
    Messages m = new Messages();
    m.addMessage("SDGSFGSDFGSDFASDG");
    return mapper.writeValueAsString(m);
    // return mapper.writeValueAsString(person);
}
catch (JsonProcessingException ex) {

        return null;
 }

}

Logging the client, I get:

Sending Get request: http://localhost:8080/Library/rest/person/1.

Receiving response code: 200. {messages=[SDGSFGSDFGSDFASDG]}

6
  • You need to use ${person} on your client side (JSP or HTML) Commented Jun 30, 2014 at 12:51
  • That sounds about right but this is a HTTP GET from a program, so so far I don't know how to do as you suggest in this scenario. Commented Jun 30, 2014 at 12:52
  • Have you written scriptlet code on the JSP to read the person? Commented Jun 30, 2014 at 12:53
  • There is no JSP. The request is being made by REST. Commented Jun 30, 2014 at 12:54
  • I am guessing there is no re-direction in your GET call. You simply want to return an Object of Type Person Commented Jun 30, 2014 at 12:58

1 Answer 1

1

If there is no re-direction from your GET call, try this:

@RequestMapping(value="/person/{personId}", method=RequestMethod.GET)
@ResponseBody
public String getPerson(@PathVariable("personId") String personId) {

    logger.info(RestController.class.getName() + ".getPerson() method called."); 

    Person person = personService.get(Integer.parseInt(personId));

    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(person);

}

Make sure you Messages class is also a POJO

public class Messages implements Serializable{

private List<String> messages;

//setters and getters for messages

}
Sign up to request clarification or add additional context in comments.

10 Comments

This worked for Person but if I try another class I get no output as per above.
Make sure Messages is a POJO with private fields and appropriate setters and getters as defined by Java standards.
Your reader is reading Object rather than Messages. Why is that? You have also used the same controller mapping for Person and Messages
I'm trying to do the following: when a method has to return validation messages via REST, I want the method to return Messages object, but if everything is good, it should return a Person.
In that case you need to have implements Serializable for Messages
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.