简体   繁体   中英

Java Jersey Web Service: consume JSON request

I have a web service made witj Java and Jersey. I want to receive a JSON request and parse the json for savethe values stores on the json on the database.

This is mi web service code:

@Path("companies")
public class Companies {

    @Path("add")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public JSONObject addCompanies(JSONObject inputJsonObj){

        String input = (String) inputJsonObj.get("company");
        String output = "The input you sent is :" + input;
        JSONObject outputJsonObj = new JSONObject();
        outputJsonObj.put("output", output);

        return outputJsonObj;
    }
}

The client side is made with AngularJS:

$scope.company = "";
    $scope.submit = function(){
        // Writing it to the server
        //      
        var dataObj = {
                company : $scope.company
        };  
        var res = $http.post('http://localhost:8080/WS-Test2/crunchify/companies/add', dataObj);
        res.success(function(data, status, headers, config) {
            $scope.message = data;
            notify("succes");
        });
        res.error(function(data, status, headers, config) {
            //alert( "failure message: " + JSON.stringify({data: data}));
            notify("fail");
        });
    };

This is the error I'm getting when I pass the JSON to the web service:

Status Code:415

And this is the request I am sending:

{"company":"Testing2"}

This is my Network tab:

在此处输入图片说明

Without further configuration, JSONObject is not something that Jersey supports. You will just need to work with Strings

public String addCompanies(String json){
    JSONObject inputJsonObj = new JSONObject(json)

    String input = (String) inputJsonObj.get("company");
    String output = "The input you sent is :" + input;
    JSONObject outputJsonObj = new JSONObject();
    outputJsonObj.put("output", output);

    return outputJsonObj.toString();
}

If you really want to use JSONObject you can check out this post .

See Also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM