1

I am trying to send a value to my dummy Rest Web Service inside a JSON string. However, the service couldn't get the value that I sent.

Firstly, my JAX-RS code is like that:

@POST
@Path("/ser1")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response convertFtoCfromInput(final BasicModel bm) throws JSONException {

    System.out.println("Value is " + bm.value);
    JSONObject jsonObject = new JSONObject();
    float celsius;
    celsius = (bm.value - 32) * 5 / 9;
    jsonObject.put("F Value", bm.value);
    jsonObject.put("C Value", celsius);

    String result = "@Produces(\"application/json\") Output: \n\nF to C Converter Output: \n\n" + jsonObject;
    return Response.status(200).entity(result).build();
}

where the BasicModel class is:

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class BasicModel {
   @XmlElement float value;
}

I am sending a POST request to the ".../ftocservice/ser1" using Postman and body of my request is:

{"value": 900.0}

When I send the request, the service couldn't get the value 900.0. It prints "Value is 0.0" and returns: {"C Value": -17.77777862548828, "F Value": 0}

Where did I do wrong? Thanks already for your help.

Resources:

stuck
  • 1,477
  • 2
  • 14
  • 30
  • instead of jsonObject, just put in map and change code to `return Response.status(200).entity(map).build();` – dkb Feb 17 '19 at 08:19
  • you are creating json object explicitly and returning it which is not required., Ref: https://stackoverflow.com/a/54684243/2987755 – dkb Feb 17 '19 at 08:19

1 Answers1

0

I solved the issue!

I removed the "XmlElement" tag from the value and made it private. I created getter and setter for it and it worked.

So, the final code of BasicModel is:

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class BasicModel {
   private float value;

   public float getValue(){
       return value;
   }

   public float setValue(float value){
       this.value = value;
   }

}
stuck
  • 1,477
  • 2
  • 14
  • 30