Search code examples
web-servicesrestjakarta-eerestlet

Capture JSON from representation and return String value


I have a working webservice as shown below which will return a double value in JSON format e.g. {"PMC":17.34}

@Override
@Post("JSON")
public Representation post(Representation entity) throws ResourceException
{
    JsonObjectBuilder response = Json.createObjectBuilder();

    try {
        String json = entity.getText(); // Get JSON input from client
        Map<String, Object> map = JsonUtils.toMap(json); // Convert input into Map
        double result = matrix.calculatePMC(map); // Calculate PMC value
        response.add("PMC", result);
    } catch (IOException e) {
        LOGGER.error(this.getClass() + " - IOException - " + e);
        getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
    }

    return new StringRepresentation(response.build().toString());       
}

Now, I would like to change the program to return just the double value, i.e. 17.34, so i modified my program to the following:

@Post
public double post(Response response)
{
    double result = 0;

    try {
        String json = response.getEntity().getText(); //Get JSON input from client
        Map<String, Object> map = JsonUtils.toMap(json); // Convert input into Map
        result = matrix.calculatePMC(map); // Calculate PMC value
    } catch (IOException e) {
        LOGGER.error(this.getClass() + " - IOException - " + e);
        getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
    }

    return result;      
}

When I run this I get a 415 Unsupported Media Type error. What am I missing?


Solution

  • Misread program requirements, it should return a String value (of a double) instead. Following is my final working program:

    @Post
    public String post(String json)
    {
        double result = 0;
        Map<String, Object> map = JsonUtils.toMap(json); // Convert JSON input into Map
        result = matrix.calculatePMC(map); // Calculate PMC value
    
        return String.valueOf(result);
    }