1

I am making the following PUT request using AJAX to a RESTful web service. Before making the request, I convert the data returned from form submission (using ng-submit) to a JSON String:

var serializedData =angular.toJson(person);

I then send it as data in an AJAX call like this:

    $http({
        method: 'PUT',
        url: myurl +person.personID,
        data: serializedData,
        headers: {
            'Content-Type': 'application/json'
        }
    }).success(function(data) {

        console.log("Success");

    });

Now in my web service, I want to get this data and create a Java object:

@PUT
    @Path("/person/{id}")
    @Produces({ MediaType.APPLICATION_JSON }) 
    @Consumes({MediaType.APPLICATION_JSON}) 
public Response updatePerson(@PathParam("id") String personID,
        @Context HttpServletRequest httpRequest) {


    Response.ResponseBuilder builder = Response.ok();
    Person person =null;
    String data =null;
    BufferedReader reader =null;
    StringBuffer buffer = new StringBuffer();
    try
    {
        reader = new BufferedReader(new InputStreamReader(httpRequest.getInputStream()));
    }
    catch (IOException e1)
    {
        e1.printStackTrace();
        e1.getCause().toString();
    }

    try
    {
        while((data =reader.readLine()) != null){
            buffer.append(data);
        }
    }
    catch (IOException e1)
    {
        e1.printStackTrace();
    }
    String bufferToString =buffer.toString();


    try
    {
        person =JSONUtil.toObject(bufferToString, new TypeReference<Person>() {});
    }
    catch (JsonParseException e1)
    {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    catch (JsonMappingException e1)
    {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    catch (IOException e1)
    {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    if (person == null) {
        builder = Response
                .status(Response.Status.NOT_FOUND.getStatusCode());
        return builder.build();
    }

    try {

        deviceService.update(dev);
        JSONUtil.toJSONString(dev);
        builder.entity(JSONUtil.toJSONString(dev));
    } catch (JsonGenerationException e) {
    } catch (JsonMappingException e) {
    } catch (IOException e) {

    return builder.build();  
}

Here is a problem I cant seem to figure out. When the ajax call is made, data does reach to the web service, which means it is a JSON string because that is what angular.toJson does [https://docs.angularjs.org/api/ng/function/angular.toJson]. After reading it with the reader and converting it to a string and passing it to the JSONUtil.toObject(bufferToString, new TypeReference<Person>() {});, it gives me a 404 status code, meaning the person object is null. Now here is the weird thing I dont understand. If I do a get request for a Person object in POSTMAN client, edit a value in that JSON and send it as body of application/json type in a PUT request (from POSTMAN), then it works. I have checked through JSONLint that the JSON string that I receive from AJAX is valid.. Why is this happening?? I passed a string to the JSONUtil.toObject(bufferToString, new TypeReference<Person>() {});, which is what that method needs. Is it not in the right format? I cant seem to understand. Any help will be appreciated. Have been stuck on this for 4 hours now. Thank you.

2 Answers 2

1

I post this as an answer since I can't comment yet. The following is a suggestion to refactor code to make it easier to mantain. If doing so is not an option, I'd suggest you post the StackTrace printed on your console to provide further assistance.

Now the suggestion: You should try JAX-B. It'd make your code much more manageable and free you from the hazzard of doing serialization and deserialization manually. You can use all JAX-B POJOs as parameters or return types:

@POST
public StatusDTO createStatus(StatusDTO dto) {
    //your code here
}

All you need to do is create a POJO and annotate it with @XmlRootElement and you can use it directly as parameter in your Jersey services.

With this you can return the POJO and JAX-B will do the serialization, so you don't have to build the response manually either. Finally, whenever you need to return an error code, try throwing a WebApplicationException.

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

2 Comments

Here is an example of a POJO annotated with @XmlRootElement, and here are some services using it and the WebApplicationException
@ Andres Thank you for guiding about using JAX-B, unfortunately I cannot suggest changing of the current solution. I have to use the existing code and the current implementation. But I surely understand your point of using JAX-B. I dont understand why the JSON string is not getting converted to a JSON object. Thank you.
0

You need other solution to work with json in Java, in Spring use Jersey and Jackson and i catch the json objects to a java pojo, check this example https://github.com/ripper2hl/angular-todo/

and the code for catch object is very simple @RequestMapping(method = RequestMethod.POST) public Todo saveTodo(@RequestBody Todo todo){ return todoDao.save(todo); }

2 Comments

I understand but I am not allowed to change the current code to a large extent. I am using Jackson for converting JSON string to a POJO.
dont convert to string your json before to send to java, send json object, try this , and check the content type , application/json for send, if continues problems i recommend create a github simple project for debug

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.